The Google Maps v3 API expands the boundaries. Javascript how-to?

function initialize(){
// Creating a map
var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(53.0123601276819, -2.44519164333635),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var m = [];

function addMarker(title, lat, lng) {
    m[m.length] = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        title: title,  
        clickable: true,
        icon: 'http://domain.com/MVC/images/full.png' 
    });

} 

addMarker('Home', 53.0682143712504, -2.52150736731894);
addMarker('Away', 53.0123601276819, -2.44519164333635);
addMarker('Away', 59.0123601276819, -2.44519164333635);    

// Create a LatLngBounds object
var bounds = new google.maps.LatLngBounds(); 

for (var i = 0; i < m.length; i++) {
  // Insert code to add marker to map here

  // Extend the LatLngBound object
  bounds.extend(m[i]);

}
alert(m[0]);
map.fitBounds(bounds);
  document.write(getBounds());   

}

This is my code.

My intention is to develop a map that shows numerous markers and copies the scale so that all the markers fit on my screen.

I am new to JS.

I understand that

var m = [];

creates an empty array.

Then every time I call addMarker(), the details are added to this array m

At the top, I set the default and center point.

Then I add various markers.

Then I go through each key in the m array and expand the boundaries using the data from this.

Then I understand that I map.fitBounds(bounds);have to redefine the scale / center, applicable for all markers.

. , / , , .

.

+3
2

LatLng bounds.extend.

:

....
bounds.extend(new google.maps.LatLng(lat, lng));
....
+7

, , , .

//make an empty bounds variable
var bounds = new google.maps.LatLngBounds();


//do your map stuff here
//special note: make sure your lat and lng are integers or googleMaps will error
var lat = 38.103;
var lng = -121.572;
bounds.extend(new google.maps.LatLng(lat, lng));


//adjust the viewport of the map
//special note: this only needs to be done once, don't put it in a loop
map.fitBounds(bounds);
+5

Source: https://habr.com/ru/post/1762471/


All Articles