最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calculate the distance between two location using google map api - Stack Overflow

programmeradmin0浏览0评论

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?

;destination=lucknow&key=%20AIzaSyCeBdq7rr-R7w7vZCXscLWgEDb3oO9CUhw

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./maps/api/directions/json?origin=kanpur&destination=lucknow&key=%20AIzaSyCeBdq7rr-R7w7vZCXscLWgEDb3oO9CUhw

Share Improve this question edited Nov 10, 2015 at 23:48 geocodezip 161k14 gold badges227 silver badges255 bronze badges asked Nov 10, 2015 at 22:36 sumitsumit 491 gold badge1 silver badge9 bronze badges 3
  • 1 Do you want driving distance (by road) or straight line distance (as the crow flies)? – geocodezip Commented Nov 10, 2015 at 23:01
  • Possible duplicate of Calculate distance between two points in google maps V3 – geocodezip Commented Nov 10, 2015 at 23:02
  • possible duplicate of Get driving distance between two points using Google Maps API – geocodezip Commented Nov 10, 2015 at 23:03
Add a ment  | 

2 Answers 2

Reset to default 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(plete) {  
    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            plete(location);
        }, function () {
            plete(null);
        });
    }
    else {
        plete(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./maps/api/js?callback=initMap"
            async defer></script>

JSFiddle

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.puteDistanceBetween(p3, p4) / 1000); //dividing by 1000 to get Kilometers
}
alert(distanceTwoPoints(p1, p2));

Fiddle example (UPDATED): https://jsfiddle/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 pute this distance, call puteDistanceBetween(), passing it two LatLng objects.

发布评论

评论列表(0)

  1. 暂无评论