在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):hibiken/react-places-autocomplete开源软件地址(OpenSource Url):https://github.com/hibiken/react-places-autocomplete开源编程语言(OpenSource Language):JavaScript 100.0%开源软件介绍(OpenSource Introduction):We are looking for maintainers!In order to ensure active development going forward, we are looking for maintainers to join the project. Please contact the project owner if you are interested. React Places AutocompleteA React component to build a customized UI for Google Maps Places Autocomplete DemoLive demo: hibiken.github.io/react-places-autocomplete/ Features
InstallationTo install the stable version npm install --save react-places-autocomplete React component is exported as a default export import PlacesAutocomplete from 'react-places-autocomplete'; utility functions are named exports import {
geocodeByAddress,
geocodeByPlaceId,
getLatLng,
} from 'react-places-autocomplete'; Getting StartedTo use this component, you are going to need to load Google Maps JavaScript API Load the library in your project <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> Create your component import React from 'react';
import PlacesAutocomplete, {
geocodeByAddress,
getLatLng,
} from 'react-places-autocomplete';
class LocationSearchInput extends React.Component {
constructor(props) {
super(props);
this.state = { address: '' };
}
handleChange = address => {
this.setState({ address });
};
handleSelect = address => {
geocodeByAddress(address)
.then(results => getLatLng(results[0]))
.then(latLng => console.log('Success', latLng))
.catch(error => console.error('Error', error));
};
render() {
return (
<PlacesAutocomplete
value={this.state.address}
onChange={this.handleChange}
onSelect={this.handleSelect}
>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
<div>
<input
{...getInputProps({
placeholder: 'Search Places ...',
className: 'location-search-input',
})}
/>
<div className="autocomplete-dropdown-container">
{loading && <div>Loading...</div>}
{suggestions.map(suggestion => {
const className = suggestion.active
? 'suggestion-item--active'
: 'suggestion-item';
// inline style for demonstration purpose
const style = suggestion.active
? { backgroundColor: '#fafafa', cursor: 'pointer' }
: { backgroundColor: '#ffffff', cursor: 'pointer' };
return (
<div
{...getSuggestionItemProps(suggestion, {
className,
style,
})}
>
<span>{suggestion.description}</span>
</div>
);
})}
</div>
</div>
)}
</PlacesAutocomplete>
);
}
} PropsPlacesAutocomplete is a Controlled Component with a Render Prop. Therefore, you MUST pass at least
valueType: onChangeType: Typically this event handler will update <PlacesAutocomplete
value={this.state.value}
onChange={value => this.setState({ value })}
>
{/* custom render function */}
</PlacesAutocomplete> childrenType: This is where you render whatever you want to based on the state of
Simple example const renderFunc = ({ getInputProps, getSuggestionItemProps, suggestions }) => (
<div className="autocomplete-root">
<input {...getInputProps()} />
<div className="autocomplete-dropdown-container">
{loading && <div>Loading...</div>}
{suggestions.map(suggestion => (
<div {...getSuggestionItemProps(suggestion)}>
<span>{suggestion.description}</span>
</div>
))}
</div>
</div>
);
// In render function
<PlacesAutocomplete value={this.state.value} onChange={this.handleChange}>
{renderFunc}
</PlacesAutocomplete>; getInputPropsThis function will return the props that you can spread over the // In render function
<input {...getInputProps({ className: 'my-input', autoFocus: true })} /> getSuggestionItemPropsThis function will return the props that you can spread over each suggestion item in your
autocomplete dropdown. You MUST call it with // Simple example
<div className="autocomplete-dropdown">
{suggestions.map(suggestion => (
<div {...getSuggestionItemProps(suggestion)}>
{suggestion.description}
</div>
))}
</div>
// Pass options as a second argument
<div className="autocomplete-dropdown">
{suggestions.map(suggestion => {
const className = suggestion.active ? 'suggestion-item--active' : 'suggestion-item';
return (
<div {...getSuggestionItemProps(suggestion, { className })}>
{suggestion.description}
</div>
);
})}
</div> loadingThis is a boolean flag indicating whether or not the request is pending, or has completed. suggestionsThis is an array of suggestion objects each containing all the data from Google Maps API and other metadata. An example of a suggestion object. {
active: false,
description: "San Francisco, CA, USA",
formattedSuggestion: { mainText: "San Francisco", secondaryText: "CA, USA" },
id: "1b9ea3c094d3ac23c9a3afa8cd4d8a41f05de50a",
index: 0,
matchedSubstrings: [ {length: 8, offset: 0} ],
placeId: "ChIJIQBpAG2ahYAR_6128GcTUEo",
terms: [
{ offset: 0, value: "San Francisco" },
{ offset: 15, value: "CA" },
{ offset: 19, value: "USA" }
],
types: ["locality", "political", "geocode"]
} onSelectType: You can pass a function that gets called instead of The function takes three positional arguments. First argument is // NOTE: `placeId` and `suggestion` are null when user hits Enter key with no suggestion item selected.
const handleSelect = (address: string, placeId: ?string, suggestion: ?object) => {
// Do something with address and placeId and suggestion
}
// Pass this function via onSelect prop.
<PlacesAutocomplete
value={this.state.value}
onChange={this.handleChange}
onSelect={this.handleSelect}
>
{/* Custom render function */}
</PlacesAutocomplete> onErrorType: You can pass Function takes // Log error status and clear dropdown when Google Maps API returns an error.
const onError = (status, clearSuggestions) => {
console.log('Google Maps API returned error with status: ', status)
clearSuggestions()
}
<PlacesAutocomplete
value={this.state.value}
onChange={this.handleChange}
onError={onError}
>
{/* Custom render function */}
</PlacesAutocomplete> searchOptionsType: You can fine-tune the settings passed to the AutocompleteService class with // these options will bias the autocomplete predictions toward Sydney, Australia with a radius of 2000 meters,
// and limit the results to addresses only
const searchOptions = {
location: new google.maps.LatLng(-34, 151),
radius: 2000,
types: ['address']
}
<PlacesAutocomplete
value={this.state.value}
onChange={this.handleChange}
searchOptions={searchOptions}
>
{/* Custom render function */}
</PlacesAutocomplete> debounceType: The number of milliseconds to delay before making a call to Google Maps API. highlightFirstSuggestionType: If set to shouldFetchSuggestionsType: // Only fetch suggestions when the input text is longer than 3 characters.
<PlacesAutocomplete
value={this.state.address}
onChange={this.handleChange}
shouldFetchSuggestions={this.state.address.length > 3}
>
{/* custom render function */}
</PlacesAutocomplete> googleCallbackNameType: If provided, component will initialize after the browser has finished downloading google script. IMPORTANT: To enable this async mode, you need to provide the same callback name to google script via Example: <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=myCallbackFunc"></script> Then, provide <PlacesAutocomplete
value={this.state.value}
onChange={this.handleChange}
googleCallbackName="myCallbackFunc"
>
{/* custom render function */}
</PlacesAutocomplete> NOTE: If there are more than one Example: <script>
window.myCallbackFunc = function() {
window.initOne && window
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论