Question

I can display the directions between two points using google api as follows:-

    if (e.keyCode == 109 && $("#booking-docket").dialog("isOpen")) {

      var pickup = $('#txt-pickup-lat-long').val();
      var destination = $('#txt-destination-lat-long').val();

      alert(pickup);
      alert(destination);

      var start = new google.maps.LatLng(52.73696,-1.3553244444444);
      var end = new google.maps.LatLng(52.781048888889,-1.2110222222222);
      var request = {
          origin:start,
          destination:end,
          travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });

    }
  • alert(pickup) = 52.73696,-1.3553244444444
  • alert(destination) = 52.781048888889,-1.2110222222222

However, when I change these values from:-

      var start = new google.maps.LatLng(52.73696,-1.3553244444444);
      var end = new google.maps.LatLng(52.781048888889,-1.2110222222222);

to:-

      var start = new google.maps.LatLng(pickup);
      var end = new google.maps.LatLng(destination);

It stops working, even though the values of pickup & destination are exactly the same as what is typed in (without using variables).

Any ideas why this is happening?

Was it helpful?

Solution

The problem is that pickup and destination are strings, which is what the jQuery .val() function returns.

The LatLng constructor expects floats. Wrap your pickup and destination values in parseFloat to convert them from string to floats.

In fact as they're actually a list, each containing two items, you'll need to split them into their two separate parts first as well.

var pickup = $('#txt-pickup-lat-long').val();
var pickupLat = pickup.split(",")[0];
var pickupLng = pickup.split(",")[1];
var start = new google.maps.LatLng(parseFloat(pickupLat), parseFloat(pickupLng));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top