从当前位置到标记

时间:2017-03-23 15:15:26

标签: api google-maps directions

使用Google地图API和路线或路线。我希望当用户点击标记时,从用户的当前位置到该标记的路线将呈现。

我一直在研究Google Maps 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>

谢谢,

1 个答案:

答案 0 :(得分:5)

我已经解决了这个问题。问题是这一行,

destination: marker.getPosition(),

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

我在设置infoWindow的函数中设置了latit和longit,它已被定义为全局变量,

// 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-pages working example