显示谷歌地图方向

时间:2019-05-08 17:20:57

标签: javascript json ajax google-maps google-maps-api-3

我正在尝试显示使用异步调用从数据库动态获取的路线。我可以很好地显示地图,但是根本无法绘制方向或标记。每当触发动作时,它就会到达我设置的地图中心。我正在使用从数据库中获取的经纬度的JSON数组。然后,我将地图方向函数称为

var mapholder = document.getElementById("mapholder");



function showPosition() {
    //Getting all the coorindates
    console.log(myObj);
    fromDirectionLat = myObj[0].lat;
    fromDirectionLong = myObj[0].long;
    toDirectionLat = myObj[1].lat;
    toDirectionLong = myObj[1].long;

    //Setting mapholder style
    mapholder.style.height = '600px';
    mapholder.style.width = '600px';
    mapholder.style.border = 'medium solid #555555';
    var latlong = new google.maps.LatLng(fromDirectionLat, fromDirectionLong);
    var myOptions = {
        center: latlong,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };


    var directionService = new google.maps.DirectionsService();
    var directionDisplay = new google.maps.DirectionsRenderer();

    var map = new google.maps.Map(document.getElementById('mapholder'), myOptions);
    directionDisplay.setMap(map);

    var onChangeHandler = function() {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    };
    document.getElementById('fromItem').addEventListener('change', onChangeHandler);
    document.getElementById('toItem').addEventListener('change', onChangeHandler);
}


function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    directionsService.route({
        origin: new google.maps.LatLng(fromDirectionLat, fromDirectionLong),
        destination: new google.maps.LatLng(toDirectionLat, toDirectionLong),
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            directionsDisplay.setDirections(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}

我得到的输出就是enter image description here

无论我如何更改原点/目的地,它们都不会绘制到屏幕上。

0 个答案:

没有答案