我正在使用Google包创建一个google-map-react地图和几个标记。坐标、infowindow、图标等信息将来自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上列出的解决方案,但也不起作用。
发布于 2020-08-18 06:31:38
根据您提供的StackOverflow的答案,他们使用new maps.Marker()创建了一个新的Google Maps标记。如果你想从json数据中获得坐标、图标和标记的不同属性的值,你需要把这个new maps.Marker()放到每个json数据的循环中。下面应该是您的ModelsMap的值。不要让get导入你的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密钥。
发布于 2021-12-01 12:11:50
从google云控制台启用javascript地图api
https://stackoverflow.com/questions/63399688
复制相似问题