问题描述
我正在使用google-map-react NPM软件包创建Google Map和几个标记。 坐标,信息窗口,图标等的信息将来自JSON文件。 我添加了onGoogleApiLoaded和yesIWantToUseGoogleMapApiInternals。
import React,{ useEffect } from 'react'
import GoogleMapReact from 'google-map-react'
let mapOptions = {
center: { lat: 39.56939,lng: -40.0000 },zoom: 3.5,disableDefaultUI: true,gestureHandling: 'none',zoomControl: false,scaleControl: false,zoomControlOptions: false,scrollwheel: false,panControl: false,};
function ModelsMap({ data,state }) {
console.log(data.models)
function initMap() {
let markers = [
/.../
];
function Marker(props) {
let marker = new google.maps.marker({
position: props.coords,content: props.content,icon: props.icon,map: map
});
let infoWindow = new google.maps.InfoWindow({
content: props.content
});
Marker.addListener('click',function () {
infoWindow.open(map,marker);
})
}
}
// useEffect(initMap,[]); it will only render once
return (
<div style={{height: '100vh',width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "YOUR_API_KEY" }}
defaultCenter={{lat: 39.56939,lng: -40.0000 }}
defaultZoom={3.5}
options={mapOptions}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map,maps }) => ModelsMap(map,maps)}
>
</GoogleMapReact>
</div>
);
}
export default ModelsMap;
我一直遵循This other stack overflow post上列出的解决方案,但这也不起作用。
解决方法
根据您提供的StackOverflow答案,他们使用new maps.Marker()
创建新的Google Maps标记。如果要从json数据中获取坐标,图标和标记的不同属性的值,则需要放置此new maps.Marker()
以遍历每个json数据。以下应该是您的ModelsMap
的值。请勿导入您的json文件。
const ModelsMap = (map,maps) => {
//instantiate array that will hold your Json Data
let dataArray = [];
//push your Json Data in the array
{
data.map((markerJson) => dataArray.push(markerJson));
}
//Loop through the dataArray to create a marker per data using the coordinates in the json
for (let i = 0; i < dataArray.length; i++) {
let marker = new maps.Marker({
position: { lat: dataArray[i].lat,lng: dataArray[i].lng },map,label: dataArray[i].id,});
}
};
这里是sample code that shows this。请使用您自己的API密钥来工作。
侧面说明:我在您的问题中删除了API密钥。将来请不要在公共站点共享您的API密钥。