未找到 Javascript/jQuery Google map 路线

标签 javascript jquery html google-maps

我有一个应用程序,它显示数据库中的邮政编码,当单击按钮时,邮政编码将被地理编码并在弹出窗口中的 Google map 上显示为标记。我试图在 map 上显示两个标记之间的行驶路线。我已将地理编码值保存到 HTML span 标记中,并尝试使用这些值作为路线的起点和目的地。除了标记之间显示的路线显示错误消息“由于 NOT_FOUND 导致方向请求失败”之外,一切正常。

知道如何才能显示路线吗?

$(document).ready(function () {

        $(".openMap").click(function () {

            var directionsService = new google.maps.DirectionsService;
            var mapLocation = $(this).prev().prev().prev().text();
            var secondMarker =  $(this).prev().prev().text();
            window.markers = [];
            var geocoder = new google.maps.Geocoder(); 

            geocoder.geocode({ address: mapLocation }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };

                    map = new google.maps.Map(document.getElementById('map'), mapOptions);

                    var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
                    directionsDisplay.setMap(map);

                    var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Departure Location" });                                                    
                markers.push(marker);
                $('#route1').text(results[0].geometry.location);
            }

        });
        var geocoder2 = new google.maps.Geocoder(); 

            geocoder.geocode({ address: secondMarker }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    var marker2 = new google.maps.Marker({ map: map, position: results[0].geometry.location,  title: "Destination Location" }); 
                markers.push(marker2);
                $('#route2').text(results[0].geometry.location);

            var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < markers.length; i++) {
            bounds.extend(markers[i].getPosition());
        }
            map.fitBounds(bounds);  
            }
        });

             directionsService.route({
             origin: $('#route1').text(),
             destination: $('#route2').text(),
             travelMode: google.maps.TravelMode.DRIVING
            }, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            } else {
            window.alert('Directions request failed due to ' + status);
            }
        });
        $("#map").dialog({ title: "Lift Location ", height: 500, width: 500, modal: true });

                });
    });

最佳答案

路线 1 和路线 2 为空。 API 不知道如何创建从“”到“”的路线。

一旦我解决了这个问题(使用包含邮政编码的 post1 和 post2),我就会收到一个 javascript 错误:Uncaught ReferenceError:directionsDisplay 未定义。

修复显示路线的问题。

proof of concept fiddle

代码片段:

$(document).ready(function() {
  var directionsDisplay;
  $(".openMap").click(function() {

    var directionsService = new google.maps.DirectionsService;
    var mapLocation = $(this).prev().prev().prev().text();
    var secondMarker = $(this).prev().prev().text();
    window.markers = [];
    var geocoder = new google.maps.Geocoder();
    var mapOptions = {
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map'), mapOptions);

    geocoder.geocode({
      address: mapLocation
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);

        directionsDisplay = new google.maps.DirectionsRenderer({
          map: map
        });
        directionsDisplay.setMap(map);

        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: "Departure Location"
        });
        markers.push(marker);
        $('#route1').text(results[0].geometry.location);
      }

    });
    var geocoder2 = new google.maps.Geocoder();

    geocoder.geocode({
      address: secondMarker
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        var marker2 = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: "Destination Location"
        });
        markers.push(marker2);
        $('#route2').text(results[0].geometry.location);

        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < markers.length; i++) {
          bounds.extend(markers[i].getPosition());
        }
        map.fitBounds(bounds);
      }
    });
    console.log("post1:" + $('.post1').text());
    console.log("post2:" + $('.post2').text());
    directionsService.route({
      origin: $('.post1').text(),
      destination: $('.post2').text(),
      travelMode: google.maps.TravelMode.DRIVING
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        if (!directionsDisplay || !directionsDisplay.getMap || (directionsDisplay.getMap() == null)) {
          directionsDisplay = new google.maps.DirectionsRenderer({
            map: map
          });
          directionsDisplay.setMap(map);
        }
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
    $("#map").dialog({
      title: "Lift Location ",
      height: 500,
      width: 500,
      modal: true
    });
    $(".selector").dialog({
      resizeStop: function(event, ui) {
        google.maps.event.trigger(map, 'resize');
      }
    });
    $(".selector").dialog({
      open: function(event, ui) {
        google.maps.event.trigger(map, 'resize');
      }
    });

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<div id="map" style="display: none;">
</div>
<span class='post1'>G1 3SL</span>
<span class='post2'>G1 2AF</span>
<br/>
<button class='openMap'>View On Map</button>
<br/>
<span id="route1"></span>
<span id="route2"></span>

关于未找到 Javascript/jQuery Google map 路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35663625/

相关文章:

javascript - 迭代 JSON 时出现问题

javascript - MVC5 : Refresh partial view on button click?

javascript - 减少通过函数传递许多对象的重复

javascript - Wordpress Divi 主题 - Accordion 切换的 anchor 链接

javascript - 创建具有自动调整大小的文本区域

javascript - ajax成功后没有加载 Kendo Treeview

javascript - Laravel + VueJS : Prevent access to pages without permission

javascript - 使用 ul 和 li 标签选择框

web-services - ajax调用失败时在vb.net中获取xhr对象

html - 创建一个不影响页面上其他元素定位的 div