@react谷歌地图使地图开放并成为POI的中心



我将@react-google-maps/api与React 17.0.2一起用于一个小型项目。我现在有一个坐标列表,当我点击各种按钮时,地图会将自己放在其中一个坐标的标记上。然而,我想关注的很多地方都是";POI";s、 他们已经内置了标记和一个信息框,其中包含正确的名称、地址和谷歌地图链接。(见此处(是否可以使地图居中并打开指定的POI?我没有找到任何相关的文件或例子。简化的当前代码如下:

const pinLocations = {
location1: { lat: 1, lng: 1 },
location2: { lat: 2, lng: 2 }
};
const Example = () => {
const { isLoaded } = useJsApiLoader({
googleMapsApiKey: API_KEY,
});
const [center, setCenter] = useState(pinLocations.location1);
function updateMap(pinLocation) {
setCenter(pinLocation);
}
return (
<GoogleMap zoom={11} position={center}>
<Marker position={center} />
</GoogleMap>

<Button onClick={() => updateMap(pinLocations.location1)}>
Location 1
</Button>
<Button onClick={() => updateMap(pinLocations.location2)}>
Location 2
</Button>
);  
}

这是可能的。我能够通过@react-google-maps/api库的反向地理编码以某种方式复制触觉地图的内容

我确实试着让它看起来像你上面的样品,下面是我所做的:

我制作了一个标记的样本阵列:

const markers = [
{
id: 1,
position: { lat: 14.5432, lng: 121.0473 }
},
{
id: 2,
position: { lat: 14.5468, lng: 121.0543 }
}
];

Map()组件内部,我制作了两个挂钩:一个用于活动标记,另一个用于infoWindow地址结果

const [activeMarker, setActiveMarker] = useState(null);
const [address, setAddress] = useState("Address");

然后这就是我构建<GoogleMap>组件的方式:

return (
<GoogleMap
onLoad={handleOnLoad}
onClick={() => setActiveMarker(null)}
mapContainerStyle={{ width: "100vw", height: "100vh" }}
>
{/*maps the array of markers above*/}
{markers.map(({ id, position }) => (
<Marker
key={id}
position={position}
onClick={() => handleActiveMarker(position, id)}
>
{/*show the infoWindow of the Active marker*/}
{activeMarker === id ? (
<InfoWindow
onCloseClick={() => setActiveMarker(null)}
options={{ maxWidth: 200 }}
>
<div>{address}</div>
</InfoWindow>
) : null}
</Marker>
))}
</GoogleMap>
);

<GoogleMap>内部的函数是handleOnLoad()(用于加载带有边界的映射(和handleActiveMarker(用于显示infoWindow并对infoWindow内部的地址进行反向地理编码(

#1

//loads the map with bounds
const handleOnLoad = (map) => {
const bounds = new google.maps.LatLngBounds();
markers.forEach(({ position }) => bounds.extend(position));
map.fitBounds(bounds);
};

#2

//function for marker onClick
const handleActiveMarker = (position, id) => {
if (id === activeMarker) {
return;
}
console.log(id);
/*this sets the current active marker 
to help in what infoWindow to open*/
setActiveMarker(id);
// console.log(position);
//start a geocoder here>>
const geocoder = new google.maps.Geocoder();
// console.log(geocoder);
geocoder
.geocode({ location: position })
.then((response) => {
if (response.results[0]) {
let fullAddress = response.results[0].formatted_address;
//this changes the address default state on infoWindow
setAddress(fullAddress);
} else {
window.alert("No results found");
}
})
.catch((e) => window.alert("Geocoder failed due to: " + e));
return;
};

我没有以编程方式包含setCenter,因为我注意到你所指的触觉地图没有。它已经自动适应了视口上的infoWindow。

如果您需要一个可复制的示例,这里有一个codesandbox链接:https://codesandbox.io/s/react-google-maps-api-multiple-markers-infowindow-forked-0zjogb?file=/src/Map.js

注意:使用您自己的API密钥

希望这能有所帮助。

最新更新