[英]Adding Marker to Google Maps in google-map-react with functional components
我正在使用google-map-react NPM package 創建 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,
});
}
};
這是一個顯示此的示例代碼。 請使用您自己的 API 密鑰才能正常工作。
旁注:我在您的問題中刪除了 API 密鑰。 以后請不要在公共網站上分享您的 API 密鑰。
從您的谷歌雲控制台啟用 javascript map api
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.