Uncaught exception when calling Google maps direct

2019-09-12 10:21发布

问题:

I am getting an Uncaught InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object error when I call the Google maps directions service - even so, the directions seem to be added to the map?

Here is the function that calls the directions service between the current location (currentPos) and a location not too far away (LatLng(52.705151, -2.741861))

    function calcRoute() {
    var start = currentPos;
    var end = new google.maps.LatLng(52.705151, -2.741861);
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.WALKING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

Here is the code that initializes the map and calls the calcRoute() function:

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

var currentPos;
var destinationPos;

var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
        zoom: 14
    };

    map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);

    directionsDisplay.setMap(map);

    var infoWindow = new google.maps.InfoWindow();

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            currentPos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);

            var marker = new google.maps.Marker({
                position: currentPos,
                map: map,
                title: "You are here"
            });

            marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')

            map.setCenter(currentPos);

            $.ajax({
                type: 'GET',
                url: $('#AddMarkersToMap').val(),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    addMarkers(data, infoWindow);
                },
                error: function () {
                    alert("Error");
                }
            });


        }, function () {
            handleNoGeolocation(true);
        });
    } else {
        handleNoGeolocation(false);
    }

    calcRoute();


}

Some Googling suggested the exception might be caused because the map hadn't loaded so I tried putting the calcRoute call like this which didn't help:

    $(function () {
        calcRoute()
    });

回答1:

Your currentPos variable is undefined when you call calcRoute.
getCurrentPosition is asynchronous and will not have executed before calcRoute and therefore not set currentPos.
If you need to use currentPos in calcRoute you should call it in the callback to getCurrentPosition to ensure that it is defined.

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
        currentPos = new google.maps.LatLng(position.coords.latitude,
                                         position.coords.longitude);

        var marker = new google.maps.Marker({
            position: currentPos,
            map: map,
            title: "You are here"
        });

        marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')

        map.setCenter(currentPos);

        $.ajax({
            type: 'GET',
            url: $('#AddMarkersToMap').val(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                addMarkers(data, infoWindow);
            },
            error: function () {
                alert("Error");
            }
        });
        calcRoute();
        //\\//\\//\\
    }, function () {
        handleNoGeolocation(true);
    });