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
  • 212,985
  • 98
  • 444
  • 485
Zabs
  • 13,252
  • 42
  • 158
  • 277

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,079
  • 1
  • 18
  • 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,182
  • 5
  • 35
  • 64