66681

Google zooming to fit all markers on that page

Question:

im having difficulties figuring this out, ive looked at examples here and on the internet but still cant manage to get it to work. I have a Google v3 map which displays a number of markers across the UK. Id like to be able to set the zoom level to cover all the markers in the area selected eg. London might have 50 markers and Glasgow may have 2...having the same zoom level for both would look slightly odd on the Glasgow page. I've read a little about the getBounds() method, but im not sure where and how to implemented it in my script. Any help would be appreciated. This is my code so far.

var gmarkers=[]; var map=null; function initialize(){ var myOptions={ zoom:10,<!--would this still be needed--> center:new google.maps.LatLng(parseFloat(gmapcentrelat),parseFloat(gmapcentrelong)), mapTypeControl:true, mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU}, navigationControl:true, mapTypeId:google.maps.MapTypeId.ROADMAP }; map=new google.maps.Map(document.getElementById("map_canvas"), myOptions); google.maps.event.addListener(map, 'click', function() { infowindow.close() }); // Read the data from example.xml downloadUrl(gmapfile,function(doc){ var xmlDoc=xmlParse(doc); var markers=xmlDoc.documentElement.getElementsByTagName("hotel"); for(var i=0;i<markers.length;i++){ // obtain the attribues of each marker var lat=parseFloat(markers[i].getAttribute("lat")); var long=parseFloat(markers[i].getAttribute("long")); var point=new google.maps.LatLng(lat,long); var star=(markers[i].getAttribute("star")); var star_html=''; if(star>1) {star_html='<img src="" alt="star" /><br />'} var hotel_id=(markers[i].getAttribute("id")); var hotel_name=(markers[i].getElementsByTagName("given_name")[0].firstChild.nodeValue); var country=(markers[i].getAttribute("country_id")); var city=(markers[i].getAttribute("city_id")); var location=(markers[i].getAttribute("location")); var filetxt=(markers[i].getAttribute("file_name")); var countrytxt=(markers[i].getAttribute("country_name")); countrytxt=countrytxt.toLowerCase(); countrytxt=countrytxt.replace(" ","_"); var citytxt=(markers[i].getAttribute("city_name")); citytxt=citytxt.toLowerCase(); citytxt=citytxt.replace(" ","_"); var html=''; // create the marker var marker=createMarker(point,html,star,hotel_id) } }) }; var infowindow=new google.maps.InfoWindow( { size:new google.maps.Size(150,50) }); function myclick(i){ google.maps.event.trigger(gmarkers[i],"click") }; function createMarker(latlng,html,star,hotel_id){ var contentString=html; var marker=new google.maps.Marker({ position:latlng, map:map, icon:'http://'+servername+'hotels/graphics/red_'+star+'_star.png', zIndex:Math.round(latlng.lat()*-100000)<<5 }); google.maps.event.addListener(marker,'click',function(){ infowindow.setContent(contentString); infowindow.open(map,marker)}); gmarkers[hotel_id]=marker};

Answer1:

Make use of <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#LatLngBounds" rel="nofollow">LatLngBounds</a>.extend() and <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map" rel="nofollow">Map</a>.fitBounds(). Below, the fullBounds rectangle will grow to include your markers as you create them. Then, simply fit the map to that rectangle when you are done creating your markers.

var fullBounds = new google.maps.LatLngBounds(); for(var i=0;i<markers.length;i++){ var lat=parseFloat(markers[i].getAttribute("lat")); var long=parseFloat(markers[i].getAttribute("long")); var point=new google.maps.LatLng(lat,long); fullBounds.extend(point); ... } map.fitBounds(fullBounds);

Recommend

  • How to intercept keyboard strokes going to Java Swing JTextField?
  • Standard deviation javascript
  • Returning value from function inside a function
  • change color of element Chrome extension
  • How to integrate Geodjango with Google Maps API 3?
  • Possible F# type inference limitation
  • Drawing a polygon over the entire map
  • Android Google Maps: Polygon or shape that hides entire map
  • Getting Latitude Longitude from GoogleMaps in TWebBrowser
  • Google map in top corner left
  • google maps autocomplete bounces back already cleared text …odd…odd…odd
  • Google Maps api v3 get start and end coordinates of a street
  • UIAlertController button function not working
  • Android Google Maps API v2 start navigation
  • How can I enlarge video fullscreen without the affected interface project in as3?
  • Jetty Server not starting: Unable to establish loopback connection
  • Seeking advice on Jetty HttpClient Hang
  • Body moving without any force applied? (Box2d)
  • does jqgrid support a multiple checkbox list for editing
  • java.lang.NoClassDefFoundError: com.parse.Parse$Configuration$Builder on below Lollipop versions
  • Jenkins: How To Build multiple projects from a TFS repository?
  • JFileChooser in front of fullscreen Swing application
  • jQuery show() function is not executed in Safari if submit handler returns true
  • Align navbar back button on right side
  • HTML download movie download link
  • Modifying destination and filename of gulp-svg-sprite
  • How to handle AllServersUnavailable Exception
  • How to model a transition system with SPIN
  • VBA Convert delimiter text file to Excel
  • ORA-29908: missing primary invocation for ancillary operator
  • Google cloud sdk not working when python points python3
  • How to disable jQuery.jplayer autoplay?
  • using HTMLImports.whenReady not working in chrome
  • How to stop GridView from loading again when I press back button?
  • Bitwise OR returns boolean when one of operands is nil
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • Android Heatmap on canvas or ImageView