Привет всем Нужна настройка справки Несколько маркеров для компонента google map в Angular 4. Я могу получить один маркер, чтобы отобразить этот код.
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 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 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 a number already, there 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
Надеюсь, это поможет!
ERROR ReferenceError: google is not defined
на ngOnit и карта не загруженаngOnInit() { setTimeout(() => { this.loadMap(); }, 1500); }
Затем переместил оставшуюся часть кода в функцию loadMap. Теперь он работает без нареканий. Спасибо за помощь @henrisycip