0

I have the next script:

        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;

    }
  });
}

I want calculate the km's between this 2 points,the end will be the input value and the start will be user gelocation, i cant find any online solutions for it. What are the google api syntx for userlocation for directions service? I need the outpot will be in km's

Ofir Ohayon
  • 367
  • 2
  • 18
  • Draw your map first, then get the user's location and then use `calcRoute` for the success callback of your geolocation code. That way you can pass it the user's position. – Andy Sep 25 '14 at 11:10
  • how i define origin:LatLng? it gives me an error "LatLng undefined". – Ofir Ohayon Sep 25 '14 at 11:35
  • can you copy it to JSFiddle. So we do not need to copy and paste it local and we can test it online! – xmux Sep 25 '14 at 12:16
  • Hi Ofir, just to get more details: the input value is a textfield? Do you need to display the map, or only got the distance? Can you please provide the html structure of you "calc" page? I assume you use jQuery mobile as you were using pageinit – Nicolas R Sep 25 '14 at 14:05

1 Answers1

1

Ofir,

Your first part of code was quite good. Here in the sample I used $( document ).on("ready", function() ... instead of your $( document ).on( "pageinit", "#calc", function() start because I don't know your html structure.

Changes made to make it work: I store the initial position when calcRoute is called, in a format that can be used further by the Directions API: latitude, longitude. It is the $("#start").val(latlng.k + ", " + latlng.B); line below:

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!"
    });
}

Then to test, I added a button calling the calcRoute:

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

And added the error treatment to always get a response and know what happened:

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);
    }
});

You can test it on jsfiddle: http://jsfiddle.net/gxjfnmdb/4/

Nicolas R
  • 13,812
  • 2
  • 28
  • 57