使用react-google-SearchBoxes从两个不同的地图中获取formatted_address的步骤如下:
npm install react-google-SearchBoxes
import React from 'react';
import { GoogleMap, LoadScript, StandaloneSearchBox } from '@react-google-maps/api';
const map1Options = {
center: { lat: 40.712776, lng: -74.005974 },
zoom: 10
};
const map2Options = {
center: { lat: 34.052235, lng: -118.243683 },
zoom: 10
};
render() {
return (
<LoadScript
googleMapsApiKey="YOUR_API_KEY"
libraries={['places']}
>
<div>
<h1>Map 1</h1>
<GoogleMap
mapContainerStyle={{ height: '400px', width: '100%' }}
options={map1Options}
>
<StandaloneSearchBox
onLoad={this.onLoadMap1SearchBox}
onPlacesChanged={this.onMap1PlacesChanged}
>
<input
type="text"
placeholder="Search for location"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</GoogleMap>
<h1>Map 2</h1>
<GoogleMap
mapContainerStyle={{ height: '400px', width: '100%' }}
options={map2Options}
>
<StandaloneSearchBox
onLoad={this.onLoadMap2SearchBox}
onPlacesChanged={this.onMap2PlacesChanged}
>
<input
type="text"
placeholder="Search for location"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</GoogleMap>
</div>
</LoadScript>
);
}
onLoadMap1SearchBox = (ref) => {
this.map1SearchBox = ref;
}
onLoadMap2SearchBox = (ref) => {
this.map2SearchBox = ref;
}
onMap1PlacesChanged = () => {
const places = this.map1SearchBox.getPlaces();
if (places.length > 0) {
const formattedAddress = places[0].formatted_address;
console.log('Map 1 - Formatted Address:', formattedAddress);
}
}
onMap2PlacesChanged = () => {
const places = this.map2SearchBox.getPlaces();
if (places.length > 0) {
const formattedAddress = places[0].formatted_address;
console.log('Map 2 - Formatted Address:', formattedAddress);
}
}
这样,当用户在两个地图中的SearchBox中搜索地点并选择后,你将能够获取到所选地点的formatted_address,并在控制台中打印出来。
请注意,以上代码示例中使用的是@react-google-maps/api库,你可以根据自己的需求选择其他适合的库或组件。
领取专属 10元无门槛券
手把手带您无忧上云