Google Maps API 3 Directions - 将行程持续时间和距离添加到 infoWindow

发布于 2024-09-24 15:55:44 字数 5922 浏览 5 评论 0原文

我现在非常接近这个,但无法完全得到我正在寻找的结果。这是一次尝试提取一系列地理位置以及标题和文本。然后将它们分配给填充在谷歌地图上的标记。我的最终目标是获取每个标记和“地图中心”标记(如果您愿意,则为中心)之间的行进距离和持续时间,并在单击单个标记时将其填充到信息窗口中。

到目前为止,我已经完成了这项工作的各个方面,除了让距离/持续时间在信息窗口中正确填充之外。我可以使用innerHTML 成功填充“地图画布”之外的div。

如果我尝试打印指定的 var 或更改 infoWindow 中 div 的内容,则该函数仅适用于第一次单击事件。之后,信息窗口显示为空白。这是工作脚本:

<head>
    <meta charset="utf-8" />
    <title>Towns Hub</title>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <style>
    .wrapper {position:relative;width:500px;height:300px;margin:30px auto;}
    #map {width:500px;height:300px;}
    .container{position:absolute;bottom:0;left:0;width:100%;z-index:999;}
    .trav-det{border:1px solid #000;float:left;padding:7px;font-size:1.5em;background: rgba(255,255,255, .85);}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class='trav-det' id='distance_road'></div>
            <div class='trav-det' id='duration'></div>
        </div>
        <div id="map"></div>
    </div>
    <script>
        var map;
        var arrMarkers = [];
        var infowindow = new google.maps.InfoWindow();
        var directionDisplay;
        var directionsService = new google.maps.DirectionsService();

        function mapInit(){
            directionsDisplay = new google.maps.DirectionsRenderer({
                suppressMarkers: true,
                preserveViewport:true
            });
            var latlng = new google.maps.LatLng(45.18929617,-109.24727440);
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map"),myOptions);
            directionsDisplay.setMap(map);
            var marker1 = new google.maps.Marker({
                position: new google.maps.LatLng(45.18929617,-109.24727440),
                map: map,
                title: 'Red Lodge, MT',
                icon: 'http://mywebsite.com/images/orange-marker.png'
            });
            $.getJSON("hub.txt", {}, function(data){
                $.each(data.places, function(i, item){
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(item.lat, item.lng),
                        map: map,
                        title: item.title
                    });
                    arrMarkers[i] = marker;

                    google.maps.event.addListener(marker, 'click', function() {
                        infowindow.setContent("<p><strong>" + item.title + "</strong><br>"+ item.description +"</p>");
                        calcRoute(this.getPosition());
                        infowindow.open(map, this);
                    });

                    function calcRoute(drive_end) {
                        var start = new google.maps.LatLng(45.18929617,-109.24727440);
                        var end = drive_end;
                        var request = {
                            origin:start, 
                            destination:end,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING,
                            unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
                        };
                        directionsService.route(request, function(response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                directionsDisplay.setDirections(response);
                                distance = response.routes[0].legs[0].distance.text;
                                duration = response.routes[0].legs[0].duration.text;
                                document.getElementById("distance_road").innerHTML = distance;
                                document.getElementById("duration").innerHTML = duration;

                            }
                        });
                    }

                });
            });
        }
        google.maps.event.addDomListener(window, 'load', mapInit);

    </script>

文本文件:

{“places”:[{ “title”:“蒙大拿州库克市”, “描述”:“文本”, “纬度”:45.02009497, “液化石油气”:-109.93234595 }, { "title": "银门,MT", “描述”:“TEXY”, “纬度”:45.00687965, “液化天然气”:-109.98979568 }, { "title": "阿布萨罗基, MT", “描述”:“文本”, “纬度”:45.52004697, “液化石油气”:-109.44136186 }, { “标题”:“蒙大拿州比林斯”, “描述”:“文本”, “纬度”:45.78333000, “液化天然气”:-108.50000000 }, { “标题”:“布里杰,MT”, “描述”:“文本”, “纬度”:45.28568200, “液化石油气”:-108.90821700 }, { “标题”:“怀俄明州科迪”, “描述”:“文本”, “纬度”:44.52313500, “液化石油气”:-109.07561100 }, { “标题”:“蒙大拿州哥伦布”, “描述”:“文本”, “纬度”:45.62617100, “液化天然气”:-109.25712600 }, { “标题”:“加德纳,MT”, “描述”:“文本”, “纬度”:45.03049875, “液化天然气”:-110.70471900 }, { “标题”:“奈,MT”, “描述”:“文本”, “纬度”:45.43584263, “液化天然气”:-109.80859757 }, { “标题”:“乔利埃特,MT”, “描述”:“文本”, “纬度”:45.48287830, “液化石油气”:-108.97241592 }]}

关于在信息窗口中填充持续时间/距离有什么想法吗?

帮助表示赞赏!

谢谢,

Sam

ps 对于任何丑陋的脚本,我深表歉意。我一边学习一边学习,并感谢任何关于使这个脚本更高效的想法!

I'm so close on this one right now, but can't quite get the result I'm looking for. This is an attempt to pull a series of geolocations - along with a title and text. These are then assigned to markers which are populated on a google map. My ultimate goal is to get the distance and duration of travel between each of the markers and the 'map-center' marker (hub if you will) and populate it in the infoWindow when an individual marker is clicked.

So far I've got every aspect of this working EXCEPT getting the distance/duration to populate correctly in the infoWindow. I can successfully populate a div outside of the 'map-canvas' with innerHTML.

If I either try to print an assigned var or change the content of a div within the infoWindow, the function only works on the first click event. After that the infoWindow shows up blank. Here is the working script:

<head>
    <meta charset="utf-8" />
    <title>Towns Hub</title>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <style>
    .wrapper {position:relative;width:500px;height:300px;margin:30px auto;}
    #map {width:500px;height:300px;}
    .container{position:absolute;bottom:0;left:0;width:100%;z-index:999;}
    .trav-det{border:1px solid #000;float:left;padding:7px;font-size:1.5em;background: rgba(255,255,255, .85);}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class='trav-det' id='distance_road'></div>
            <div class='trav-det' id='duration'></div>
        </div>
        <div id="map"></div>
    </div>
    <script>
        var map;
        var arrMarkers = [];
        var infowindow = new google.maps.InfoWindow();
        var directionDisplay;
        var directionsService = new google.maps.DirectionsService();

        function mapInit(){
            directionsDisplay = new google.maps.DirectionsRenderer({
                suppressMarkers: true,
                preserveViewport:true
            });
            var latlng = new google.maps.LatLng(45.18929617,-109.24727440);
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map"),myOptions);
            directionsDisplay.setMap(map);
            var marker1 = new google.maps.Marker({
                position: new google.maps.LatLng(45.18929617,-109.24727440),
                map: map,
                title: 'Red Lodge, MT',
                icon: 'http://mywebsite.com/images/orange-marker.png'
            });
            $.getJSON("hub.txt", {}, function(data){
                $.each(data.places, function(i, item){
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(item.lat, item.lng),
                        map: map,
                        title: item.title
                    });
                    arrMarkers[i] = marker;

                    google.maps.event.addListener(marker, 'click', function() {
                        infowindow.setContent("<p><strong>" + item.title + "</strong><br>"+ item.description +"</p>");
                        calcRoute(this.getPosition());
                        infowindow.open(map, this);
                    });

                    function calcRoute(drive_end) {
                        var start = new google.maps.LatLng(45.18929617,-109.24727440);
                        var end = drive_end;
                        var request = {
                            origin:start, 
                            destination:end,
                            travelMode: google.maps.DirectionsTravelMode.DRIVING,
                            unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
                        };
                        directionsService.route(request, function(response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                directionsDisplay.setDirections(response);
                                distance = response.routes[0].legs[0].distance.text;
                                duration = response.routes[0].legs[0].duration.text;
                                document.getElementById("distance_road").innerHTML = distance;
                                document.getElementById("duration").innerHTML = duration;

                            }
                        });
                    }

                });
            });
        }
        google.maps.event.addDomListener(window, 'load', mapInit);

    </script>

text file:

{"places": [{
"title": "Cooke City, MT",
"description": "TEXT",
"lat": 45.02009497,
"lng": -109.93234595
},
{
"title": "Silver Gate, MT",
"description": "TEXY",
"lat": 45.00687965,
"lng": -109.98979568
},
{
"title": "Absarokee, MT",
"description": "TEXT",
"lat": 45.52004697,
"lng": -109.44136186
},
{
"title": "Billings, MT",
"description": "TEXT",
"lat": 45.78333000,
"lng": -108.50000000
},
{
"title": "Bridger, MT",
"description": "TEXT",
"lat": 45.28568200,
"lng": -108.90821700
},
{
"title": "Cody, WY",
"description": "TEXT",
"lat": 44.52313500,
"lng": -109.07561100
},
{
"title": "Columbus, MT",
"description": "TEXT",
"lat": 45.62617100,
"lng": -109.25712600
},
{
"title": "Gardiner, MT",
"description": "TEXT",
"lat": 45.03049875,
"lng": -110.70471900
},
{
"title": "Nye, MT",
"description": "TEXT",
"lat": 45.43584263,
"lng": -109.80859757
},
{
"title": "Joliet, MT",
"description": "TEXT",
"lat": 45.48287830,
"lng": -108.97241592
}]}

Any ideas about populating the duration/distance in the infoWindow?

Help appreciated!

Thanks,

Sam

ps I apologize for any ugly scripting. I'm learning as I go and appreciate any thoughts on making this script more efficient!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

站稳脚跟 2024-10-01 15:55:45

我可能是错的,但从你的代码来看:

<div class="wrapper">
    <div class="container">
        <div class='trav-det' id='distance_road'></div>
        <div class='trav-det' id='duration'></div>
    </div>
</div>

你正在用距离/持续时间在 dom 中填充 div。
假设信息出现在 div 中,没问题...
要将其放入信息窗口,您需要使用:

 infowindow.setContent(" distance: "+distance+"<br> duration: "+duration+" ")

i might be wrong but from looking at your code:

<div class="wrapper">
    <div class="container">
        <div class='trav-det' id='distance_road'></div>
        <div class='trav-det' id='duration'></div>
    </div>
</div>

you are poulating divs in the dom with the distance/duration.
assuming the info is appearing in the divs ok...
to get it into the info window you would need to use:

 infowindow.setContent(" distance: "+distance+"<br> duration: "+duration+" ")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文