1

I have a requirement to calculate and print the distance from current location to given destination. As per my understanding, i can achieve this by google Map api.

So, I will have to pass only destination location and api will the map as well as distance.

For that I have configured on google and got the below link, I am not able to understand how to use this, but in below url I am passing the source and destination, but I don't want to pass the source, it should be taken current location as source.

Is it possible to print the distance on web page?

https://maps.googleapis.com/maps/api/directions/json?origin=kanpur&destination=lucknow&key=%20AIzaSyCeBdq7rr-R7w7vZCXscLWgEDb3oO9CUhw

geocodezip
  • 158,664
  • 13
  • 220
  • 245
sumit
  • 49
  • 1
  • 1
  • 9
  • 1
    Do you want driving distance (by road) or straight line distance (as the crow flies)? – geocodezip Nov 10 '15 at 23:01
  • Possible duplicate of [Calculate distance between two points in google maps V3](http://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google-maps-v3) – geocodezip Nov 10 '15 at 23:02
  • possible duplicate of [Get driving distance between two points using Google Maps API](http://stackoverflow.com/questions/29003118/get-driving-distance-between-two-points-using-google-maps-api) – geocodezip Nov 10 '15 at 23:03

2 Answers2

2

It looks like you are looking for a Directions service but since:

but I don't want to pass the source, it should be taken current location as source.

below is provided the modified example from Directions service page that demonstrates how to specify current location for Directions service

function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 7,
        center: { lat: 41.85, lng: -87.65 }
    });
    directionsDisplay.setMap(map);

    var printRoute = function () {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    };

    getCurrentLocation(function (loc) {
        if (loc != null) {
            document.getElementById('startInner').value = loc.toString();
            document.getElementById('start').innerHTML = 'Current location';
            map.setCenter(loc);
        }
        else {
            document.getElementById('start').innerHTML = 'Current location not found';
            document.getElementById('btnCalc').disabled = true;
        }  
    });

    document.getElementById('btnCalc').addEventListener('click', printRoute);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    directionsService.route({
        origin: document.getElementById('startInner').value,
        destination: document.getElementById('end').value,
        travelMode: google.maps.TravelMode.DRIVING
    }, function (response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}


function getCurrentLocation(complete) {  
    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            complete(location);
        }, function () {
            complete(null);
        });
    }
    else {
        complete(null);
    }
}
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#map {
    height: 100%;
}

#floating-panel {
    position: absolute;
    top: 10px;
    left: 25%;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
    text-align: center;
    font-family: 'Roboto','sans-serif';
    line-height: 30px;
    padding-left: 10px;
}
<div id="floating-panel">
        <b>Start: </b>
        <span id="start">Current Location</span>
        <b>End: </b>
        <input id="end" type="text" ></input>
        <input id="startInner" type="hidden"></input>
        <button id="btnCalc">Print route</button>
    </div>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
            async defer></script>

JSFiddle

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
0

Here is an example on how to do this:

Code:

var p1 = new google.maps.LatLng(20, 9.4);
var p2 = new google.maps.LatLng(60.23, 9.7);

function distanceTwoPoints(p3, p4){
  return (google.maps.geometry.spherical.computeDistanceBetween(p3, p4) / 1000); //dividing by 1000 to get Kilometers
}
alert(distanceTwoPoints(p1, p2));

Fiddle example (UPDATED): https://jsfiddle.net/wexd3spp/12/

If you want to print it on the page I suggest to use the standard output method:

document.getElementById("demo").innerHTML = distanceTwoPoints(p1,p2)+" Km";

Here is what the documentation says about it:

The distance between two points is the length of the shortest path between them. This shortest path is called a geodesic. On a sphere all geodesics are segments of a great circle. To compute this distance, call computeDistanceBetween(), passing it two LatLng objects.

EugenSunic
  • 13,162
  • 13
  • 64
  • 86