13

With Google Maps I can enter a single lat/lng coordinate and the map is drawn with that lat/lng in the center.

What I'd like to be able to do is enter two coordinate pairs, say the southwest coordinate and the northeast coordinate, and have a Google Map displayed with the appropriate zoom so that the map fills the bounds defined by those coordinates.

Is this possible? If so, how?

Thanks

And the Answer is... Go to Google Maps Code Playground!

Per Taylor's suggestion, I went to the Google Maps Code Playground and entered the following code and was able to get a centered map with the appropriate zoom level bounded by the coordinate pair.

function initialize() {
  var mapDiv = document.getElementById('map-canvas');
  var map = new google.maps.Map(mapDiv, {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var southWest = new google.maps.LatLng(..., ...);
  var northEast = new google.maps.LatLng(..., ...);
  var bounds = new google.maps.LatLngBounds(southWest,northEast);
  map.fitBounds(bounds);
}

2

2 Answers 2

14

The function you are looking for is called fitBounds. The fitBounds function takes a LatLngBounds as its parameter. You can read more about that here.

Example code:

var southWest = new google.maps.LatLng(36.90731625763393,-86.51778523864743);
var northEast = new google.maps.LatLng(37.02763411292923,-86.37183015289304);
var bounds = new google.maps.LatLngBounds(southWest,northEast);
myMap.fitBounds(bounds);
5
  • Taylor: Is it possible to do this from the maps.google.com website without having to use their API? Commented Feb 1, 2013 at 22:11
  • No, not that I am aware of. What is your use case for this?
    – Taylor H.
    Commented Feb 1, 2013 at 23:12
  • I have a variety of coordinate pairs (around 10) and I want to print a map for each coordinate pair. I've used Google Maps API before so I could whip up some code, but I was hoping I could just go to the maps.google.com site, enter my first set of coordinates, hit print, enter the second set, etc. Commented Feb 1, 2013 at 23:15
  • 2
    Try playing around with the Google Code Playground Maps section. You can edit the javascript and html and run it right there. If nothing else it will help you set up your code.
    – Taylor H.
    Commented Feb 2, 2013 at 5:03
  • Taylor, the Google Code Playground Maps section was perfect and fit my needs. Thank you for your time and assistance on this matter. Commented Feb 4, 2013 at 16:23
0

Even simpler is embed the link in an Iframe element in a web page. Take the link at the livel zoom you like, framing your area of interest in a nice way. You could try it out on google sites with a free website, then cut and paste the code into your application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.