0

Done some Google Mpas stuff by myself, but stopped on distance calculating. I have a function for locating users current location marker:

function myLocationMarker(latLng) {
    var markerOptions = {
        position: latLng,
        map: map,
        clickable: true
    }
    var myMarker = new MarkerWithLabel(markerOptions);

And this function places other markers. I get the data from database, and it places about 1000 markers.

var markers = []; //blank array from markers
function addMarker(lat, lng, info) { //info - needed for database
    var pt = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({ //marker options
        position: pt,
        icon: icon,
        map: map
    });
    markers.push(marker); //pushing every marker to markers array

But what I need is distance between them. How I can calculate distance between myLocationMarker and every other marker on map from addMarker function?

user2314737
  • 27,088
  • 20
  • 102
  • 114
Brock
  • 161
  • 7

1 Answers1

2

You can use the directionsService being aware that the distance between two markers on a map depends on the travelling mode you choose ("DRIVING", "WALKING", "BICYCLING", "TRANSIT").

If you want to compute air distance you will need some geometry with the Haversine formula (check the code here: https://stackoverflow.com/a/1502821/2314737)

Here's an example with "DRIVING"

function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB, outputTxt) {
  var selectedMode = "DRIVING";
  directionsService.route({
    origin: pointA,
    destination: pointB,
    unitSystem: google.maps.UnitSystem.METRIC,
    travelMode: google.maps.TravelMode[selectedMode]
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);

      outputTxt.innerHTML = Math.round(directionsDisplay.getDirections().routes[directionsDisplay.getRouteIndex()].legs[0].distance.value / 1000) + "Km";
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

Here's a demo http://jsfiddle.net/user2314737/fLogwsff/

EDIT: alternatively, you can use the computeDistanceBetween function from the spherical geometry package

computeDistanceBetween(from:LatLng, to:LatLng, radius?:number)
Return Value: number Returns the distance, in meters, between two LatLngs. You can optionally specify a custom radius. The radius defaults to the radius of the Earth.

var distance = google.maps.geometry.spherical.computeDistanceBetween(pointA, pointB);
// by default distance is in meters
distance = Math.round(distance/ 1000) + "Km";

Updated demo: http://jsfiddle.net/user2314737/qxrg4o3y/

Community
  • 1
  • 1
user2314737
  • 27,088
  • 20
  • 102
  • 114