google maps - using map.fitBounds (bounds);

匿名 (未验证) 提交于 2019-12-03 08:30:34

问题:

I'm new to javascript and still finding the google maps javascript a bit confusing.

I have the following code (Bottom), it's javascript imbedded 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. Confused!

回答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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!