Answer the question
In order to leave comments, you need to log in
How to dynamically create markers on Google Maps API from array after processing by GeoCoder?
The task is to dynamically add markers on the map after processing the array by the geocoder at the address, in the future, instead of the array, I will take data from the database. Tell me how to implement it, while from the Google documentation I figured out how to do the following, but even everything is bad.
<!DOCTYPE html>
<html>
<head>
<title>Geocoding service</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var geocoder;
var map;
var address = new Array ('Moscow', 'Kurgan');
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(61.52401, 105.31875600000001),
zoom: 3
});
geocoder = new google.maps.Geocoder();
codeAddress(geocoder, map);
}
for (i=0; i<adress.length; i++) {
function codeAddress(geocoder, map) {
geocoder.geocode({'address': adress[i]}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
};
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API-KEY&callback=initMap">
</script>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
CodeAddress function declaration - remove the loop; pass the address as a parameter to the function itself:
function codeAddress(address, geocoder, map) {
geocoder.geocode({ address }, function(results, status) {
if (status === 'OK') {
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
address.forEach(n => codeAddress(n, geocoder, map));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question