C
C
Cheizer2019-08-01 19:10:17
JavaScript
Cheizer, 2019-08-01 19:10:17

How to set the starting position for a map from a set of addresses in the Google maps API?

Friends, I really need help, I broke my whole head, there is a Google map, with an array of addresses:

var locations = [
['Москва, Россия', 'Москва', 'infowindow 1'],
['Барнаул, Россия', 'Барнаул', 'infowindow 2'],
['Улан-Удэ, Россия', 'Улан-Удэ', 'infowindow 3']
];

Next, we get the position on the map from the addresses using the geocode function and place markers on the map in a loop, and by clicking we move over them.
But the trouble is, when loading the map, the center of the map is placed on the LAST element of the array, on the last address, on the last marker. And I need it for the first time, I can’t imagine how to do it, I’ve already tried everything :( help please.
Here I raised an example

As you can see, the initial address is set to Ulan-Ude, but you need to Moscow. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2019-08-02
@Cheizer

We throw a flag into the geocoder function, for which address we set the center of the map

for (var i = 0; i < locations.length; i++) {
        geocodeAddress(locations[i], i == 0);
}

And already there we check it and set the center
function geocodeAddress(location, isSetToCenterMap) {
  geo.geocode({'address' : location[0]}, function (results,status) {
    if(status == google.maps.GeocoderStatus.OK) {   
      if (isSetToCenterMap) {
          map.setCenter(results[0].geometry.location);
      }
      createMarker(results[0].geometry.location,location[0],location[1],location[2]);
    }
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question