google maps - using map.fitBounds (bounds);

2020-07-24 04:23发布

问题:

I have the following code (Bottom), it's javascript embedded in php to create my google map with a bunch of markers. So I want to set the zoom to a level where it will show all my markers. I understand I need this code:

var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
      latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);

To set the boundary, but I can't figure out where I should put this or what changes I need to make to the code I'm using which is below:

$zoom = 10;
$markers = '';
$mrtallyman = 1;
foreach($locations as $location) {
    $markers .= 'var myLatlng = new google.maps.LatLng'.$location[1].';
                    var marker'.$mrtallyman.' = new google.maps.Marker({
                      position: myLatlng,
                      map: map,
                      title:"'.$location[0].'",
                      icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='.$mrtallyman.'|FF776B|000000",
                    });'; 
    $mrtallyman++;
}
echo '
<script type="text/javascript">
  function initialize() {
    var userLocation = "'.$area.'";
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {"address": userLocation}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latLng = results[0].geometry.location;
            var mapOptions = {
              center: latLng,
              zoom: '.$zoom.',
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("searchPageMap"), mapOptions);
            '.$markers.'
        } else {
           alert("Geocode failed. Reason: " + status);
        }
     });
 }
  google.maps.event.addDomListener(window, "load", initialize);
</script>';

Can anyone help me out here?

回答1:

Use the principle of that code.

  1. create an empty google.maps.LatLngBounds object

    var latlngbounds = new google.maps.LatLngBounds();
    
  2. add all the places that you want to be shown to it. They need to be google.maps.LatLng objects

    $markers .= 
    'var myLatlng = new google.maps.LatLng'.$location[1].';
    latlngbounds.extend(myLatlng);
    var marker'.$mrtallyman.' = new google.maps.Marker({
                  position: myLatlng,
                  map: map,
                  title:"'.$location[0].'",
                  icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='.$mrtallyman.'|FF776B|000000",
                });'; 
    
  3. after all the places have been added to the bounds (after the foreach loop closing bracket), call map.fitBounds

    map.fitBounds(latlngbounds);