谷歌地图directionsService() - angularJs

Google maps directionsService() - angularJs

本文关键字:angularJs directionsService 谷歌地图      更新时间:2023-09-26

嗨,我有一个问题:)在AngularJS中,我为G-maps API "DirectionsStatus"创建模块。模块检查我的位置(地理位置)下一个用户选择"目的地"并创建"地图方向"。一切看起来都很好,但确实创造了"地图方向"。HTML:

<div class="wrapp" ng-controller="googlemapoutput">
            <div id="map-canvas" style="height: 400px;"></div>
             <div class="row">
                <select id="end">
                    <option> 
                        Floriańska 42, 38-200 Jasło, Polska
                    </option>
                    <option>
                        Zegrzyńska 1, Legionowo, Polska
                    </option>
                </select>
                <button id="btn" ng-click="calcRoute()">
                    Jak dojechać ?
                </button>
            </div>
        </div>

JS:

angular.module('starter.controllers', [])
.controller('googlemapoutput', function ($scope) {
    var map;
    var mapOptions;
    var directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: true
    });
    var directionsService = new google.maps.DirectionsService();
    $scope.initialize = function () {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = new google.maps.LatLng(
            position.coords.latitude,
            position.coords.longitude);
            var mapOptions = {
                zoom: 18,
                center: pos
            };
            map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
            var marker = new google.maps.Marker({
                position: pos,
                map: map
            });
        });
    };
    $scope.calcRoute = function () {
        navigator.geolocation.getCurrentPosition(function (position) {
            var end = document.getElementById('end').value;
            var pos = new google.maps.LatLng(
            position.coords.latitude,
            position.coords.longitude);
            var request = {
                origin: pos,
                destination: end,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    console.log(status);
                }
            });
        });
    };
    google.maps.event.addDomListener(window, 'load', $scope.initialize);
});

谢谢你的帮助

问题是您没有告诉directionsDisplay对象它与哪个映射相关联。您可以在调用setDirections之前(或之后)添加这一行。

if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setMap(map);
    directionsDisplay.setDirections(response);
}

或者你可能会更好地做,当你创建地图,在initialize函数:

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);