2

I'd like to calculate the distance between a marker and the the very center of the map - can anyone explain how I do this?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Zabs
  • 13,852
  • 45
  • 173
  • 297

2 Answers2

14

You can use the geometry library to solve this. You'll need to specify it when loading the Maps JS:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>

Then, in your application's code:

var center = map.getCenter();
var markerLatLng = marker.getPosition();
var distance = google.maps.geometry.spherical.computeDistanceBetween(center, markerLatLng);

This returns the distance in meters.

Mike Jeffrey
  • 3,149
  • 1
  • 19
  • 18
0

The marker is usually set using coordinates, like this: http://code.google.com/apis/maps/documentation/javascript/overlays.html#Markers

And here's a great thread about getting bounds and identifying where the map is centered: Google Map API v3 — set bounds and center

So, now that you have two sets of coordinates, use this formula to calculate the distance: http://www.movable-type.co.uk/scripts/latlong.html

Community
  • 1
  • 1
Sologoub
  • 5,312
  • 6
  • 37
  • 65