大家好,需要帮助在Angular 4中为Google Map组件设置多个标记。我可以用此代码显示一个标记。
ngOnInit() {
const myLatlng = new google.maps.LatLng(40.748817, -73.985428);
const mapOptions = {
zoom: 13,
center: myLatlng,
scrollwheel: false
};
const map = new google.maps.Map(document.getElementById('map'), mapOptions);
const Marker = new google.maps.Marker({
position: myLatlng,
title: 'Hello World!'
});
// To add the marker to the map, call setMap();
Marker.setMap(map);
}
如何修改它以显示多个位置。我从JSON中获取位置,如下所示。
{
"locations": [
{
"_id": "59eb784fa8e0be0004fb466e",
"updatedAt": "2017-10-21T16:39:43.338Z",
"createdAt": "2017-10-21T16:39:43.338Z",
"latitude": "0.2346285",
"longitude": "32.4352628",
"locationName": "Prime warehouse A",
"locationInfo": "Kampala Warehouse #001",
"__v": 0
},
{
"_id": "1568eb54560be000456466e",
"updatedAt": "2018-10-21T16:39:43.448Z",
"createdAt": "2016-09-11T16:39:43.338Z",
"latitude": "4.3346285",
"longitude": "32.4352628",
"locationName": "Prime warehouse A",
"locationInfo": "Kampala Warehouse #001",
"__v": 0
}
]
}
最佳答案
只要您可以访问locations
数组,就可以遍历该数组,并在此循环创建一个标记。
如果将所有内容放入ngOnInit
函数,请参见以下示例:
ngOnInit() {
let map;
const locations; // if you have your locations hard-coded, else just make sure it's accessible
const myLatlng = new google.maps.LatLng(40.748817, -73.985428);
const mapOptions = {
zoom: 13,
center: myLatlng,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// loop through each object of your locations array
for (let location in locations) {
// The marker's position property needs an object like { lat: 0, lng: 0 };
// Number(location.latitude) is there to convert the string to a number, but if it's a number already, there's no need to cast it further.
let latLng = {lat: Number(location.latitude), lng: Number(location.longitude)};
// Set the position and title
let marker = new google.maps.Marker({
position: latLng,
title: location.locationName
})
// place marker in map
marker.setMap(map)
}
}
您可以通过Google's official documentation了解更多有关将数据导入地图的信息。
希望有帮助!