api - 从当前位置到标记的 Google map API 路线

标签 api google-maps directions

使用 Google map API 和路线或方向。我希望这样当用户单击标记时,从用户当前位置到该标记的路线将呈现。

我一直在研究谷歌地图API文档方向服务示例here .

这是我调整它的尝试。对我来说,这似乎应该有效,所以我错过了什么?用户当前位置和标记之间的路线或方向未呈现。

<!DOCTYPE html>
<html>

<body>

    <h1>My First Google Map</h1>

    <div id="googleMap" style="width:60%;height:800px;"></div>

    <script>
        var myLatLng;

        function geoSuccess(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;
            myLatLng = {
                lat: latitude,
                lng: longitude
            };
            var mapProp = {
                //            center: new google.maps.LatLng(latitude, longitude), // puts your current location at the centre of the map,
                zoom: 15,
                mapTypeId: 'roadmap',

            };
            var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;

            //call renderer to display directions
            directionsDisplay.setMap(map);

            var bounds = new google.maps.LatLngBounds();
            //        var mapOptions = {
            //            mapTypeId: 'roadmap'
            //        };


            // Multiple Markers
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: 'My location'
            });
            var markers = [
                ['Ragazzi', 53.201472, -6.111626],
                ['McDonalds', 53.200482, -6.111337],
                ['my location', latitude, longitude]
            ];

            // Info Window Content
            var infoWindowContent = [
                ['<div>' +
                    '<h3>Ragazzi</h3>' +
                    '<p>Cafe eatin place.</p>' + ' <button onclick="calculateAndDisplayRoute(marker, i)"> Get Directions</button>' + '</div>'
                ],
                ['<div class="info_content">' +
                    '<h3>McDonalds</h3>' +
                    '<p>Excellent food establishment, NOT!.</p>' + '<button onclick="calculateAndDisplayRoute(marker, i)"> Get Directions</button>' +
                    '</div>'
                ]
            ];

            // Display multiple markers on a map
            var infoWindow = new google.maps.InfoWindow(),
                marker, i;

            // Loop through our array of markers & place each one on the map
            for (i = 0; i < markers.length; i++) {
                var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
                bounds.extend(position);
                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: markers[i][0]
                });

                // Allow each marker to have an info window
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infoWindow.setContent(infoWindowContent[i][0]);
                        infoWindow.open(map, marker);
                    }
                })(marker, i));

                marker.addListener('click', function() {

                    directionsService.route({
                        // origin: document.getElementById('start').value,
                        origin: myLatLng,
                        destination: marker.getPosition(),
                        travelMode: 'DRIVING'
                    }, function(response, status) {
                        if (status === 'OK') {
                            directionsDisplay.setDirections(response);
                        } else {
                            window.alert('Directions request failed due to ' + status);
                        }
                    });

                });
                // Automatically center the map fitting all markers on the screen
                map.fitBounds(bounds);
            }
        }

        // function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        //     directionsService.route({
        //         // origin: document.getElementById('start').value,
        //         origin: myLatLng,
        //         destination: marker.getPosition(),
        //         travelMode: 'DRIVING'
        //     }, function(response, status) {
        //         if (status === 'OK') {
        //             console.log('all good');
        //             directionsDisplay.setDirections(response);
        //         } else {
        //             window.alert('Directions request failed due to ' + status);
        //         }
        //     });
        // }

        function geoError() {
            alert("Geocoder failed.");
        }

        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
                // alert("Geolocation is supported by this browser.");
            } else {
                alert("Geolocation is not supported by this browser.");
            }
        }
    </script>

    <script async src="https://maps.googleapis.com/maps/api/js?key=api key here"></script>

</body>

</html>

谢谢,

最佳答案

我已经解决了这个问题。问题是线路,

destination: marker.getPosition(),

不正确。这给了我当前位置的坐标,而不是单击的标记。

我在设置 infoWindow 的函数中设置了纬度和经度,它们已被定义为全局变量,
// Allow each marker to have an info window
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.open(map, marker);
                    latit = marker.getPosition().lat();
                    longit = marker.getPosition().lng();
                    // console.log("lat: " + latit);
                    // console.log("lng: " + longit);
                }
            })(marker, i));

然后将这些设置为目的地,
        marker.addListener('click', function() {
            directionsService.route({
                // origin: document.getElementById('start').value,
                origin: myLatLng,

                // destination: marker.getPosition(),
                destination: {
                    lat: latit,
                    lng: longit
                },
                travelMode: 'DRIVING'
            }, function(response, status) {
                if (status === 'OK') {
                    directionsDisplay.setDirections(response);
                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });

        });

完整代码是here on github .

一个 gh 页 working example .

关于api - 从当前位置到标记的 Google map API 路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980100/

相关文章:

javascript - 谷歌地图API折线绘制不正确

javascript - 带标签的 Google Maps API v3 标记

VB.Net 按标题关闭窗口

c# - 用于 HID (USB) 的 .NET API?

java - 使用 Java 中的 api 在 Skype 中添加联系人/ friend

ios - Google Directions API 无法在 iOS 中返回结果

javascript - 请求实体太大 - 谷歌地图方向错误 413

ruby-on-rails - Rails 试图通过机架攻击来限制我的 API。不确定它是否有效?

javascript - Google map 上的 Openlayers WMS getfeatureinfo 问题

javascript - 谷歌地图 API : ignore seasonal restrictions in DirectionService request