Jquery Google Maps Местоположение пользователя

У меня есть следующий скрипт:

        var directionDisplay;
$( document ).on( "pageinit", "#calc", function() {

    directionsDisplay = new google.maps.DirectionsRenderer();
    var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434);  // Default to Hollywood, CA when no geolocation support
    if ( navigator.geolocation ) {
        function success(pos) {
            // Location found, show map with these coordinates
            drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
        }
        function fail(error) {
            drawMap(defaultLatLng);  // Failed to find location, show default map
        }
        // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
        navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
    } else {
        drawMap(defaultLatLng);  // No geolocation support, show default map
    }
    function drawMap(latlng) {
        var myOptions = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true
        };

        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        // Add an overlay to the map of current lat/lng
        directionsDisplay.setMap(map);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: "Greetings!"

        });

    }

});
var directionsService = new google.maps.DirectionsService();

function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var distanceInput = document.getElementById("distance");
      distanceInput.value = response.routes[0].legs[0].distance.value / 1000;

    }
  });
}

Я хочу вычислить километры между этими двумя точками, конечным значением будет входное значение, а начальным будет местоположение пользователя, я не могу найти никаких онлайн-решений для этого. Что такое Google Api syntx для определения местоположения пользователей для службы маршрутов? Мне нужен выход будет в км

1 ответ

Решение

Офир,

Ваша первая часть кода была довольно хорошей. Вот в примере, который я использовал $( document ).on("ready", function() ... вместо вашего $( document ).on( "pageinit", "#calc", function() начать, потому что я не знаю вашу структуру HTML.

Внесены изменения, чтобы он работал: я сохраняю исходную позицию, когда calcRoute вызывается в формате, который может использоваться в дальнейшем API-интерфейсом Directions: latitude, longitude, Это $("#start").val(latlng.k + ", " + latlng.B); строка ниже:

function drawMap(latlng) {
    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };

    // Log position in start input field
    $("#start").val(latlng.k + ", " + latlng.B);

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    // Add an overlay to the map of current lat/lng
    directionsDisplay.setMap(map);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "Greetings!"
    });
}

Затем, чтобы проверить, я добавил кнопку вызова calcRoute:

$("#calcBtn").click(function() {
    calcRoute();
});

И добавил обработку ошибок, чтобы всегда получать ответ и знать, что произошло:

directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        var distanceInput = document.getElementById("distance");
        console.log(response);
        distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
    } else {
        alert("Destination not found, error status: " + status);
    }
});

Вы можете проверить это на jsfiddle: http://jsfiddle.net/gxjfnmdb/4/

Другие вопросы по тегам