Tom Bauer
Tom Bauer

Reputation: 185

Get N Markers that are closest to the center in Google Maps

I'm trying to figure out how to sort the first 10 Markers on a Google map by distance from the center of the map in Javascript. So, let's say I have 100 Markers in an array, and I want to display more information about the first 10 closest markers in a HTML unordered list. How would I go about doing that? I found a similar example for Google Maps API version 2 here, but nothing for version 3.

Upvotes: 7

Views: 5425

Answers (3)

Adam
Adam

Reputation: 1755

There are a few questions like this on StackOverflow but none of them really show a complete example that is easy to read and understand, so I put one together. This is using the lodash/underscore sortBy function for the sorting.

const map = new google.maps.Map('#map', { center: { lat: 47.6541773, lng: -122.3500004 } });
const markers = [
  new google.maps.Marker({ position: { lat: 47.6485476, lng: -122.3471675 }, map }),
  new google.maps.Marker({ position: { lat: 47.6606304, lng: -122.3651889 }, map })
  // ...
];
const sortedMarkers = _.sortBy(markers, marker => {
  google.maps.geometry.spherical.computeDistanceBetween(
    marker.position,
    map.getCenter()
  )
});
const firstTenSortedMarkers = sortedMarkers.slice(10);

The sortBy function iterates through each marker in the array and sorts the list based on the value returned by the function that is it's second argument. The computeDistanceBetween function returns a number representing the distance in meters between the map center and the marker position, which is easy to sort on.

Upvotes: 0

alex
alex

Reputation: 490597

  1. Sort the array by proximity to your map's centre point. Use sort().
  2. Slice the first 10 with slice().
  3. Plot these on the map.

Upvotes: 0

slawekwin
slawekwin

Reputation: 6310

Whatever happens You need to calculate all distances. You can do it yourself with simple equations or use Google's geometry library: http://code.google.com/intl/pl-PL/apis/maps/documentation/javascript/geometry.html and its function: computeDistanceBetween(). Then store distance in custom marker property like e.g:

marker.distance = google.maps.geometry.spherical.computeDistanceBetween(marker.position, center.position);

and sort it anyway you want. Hope it helps.

Upvotes: 17

Related Questions