谷歌地图不显示路线

Posted

技术标签:

【中文标题】谷歌地图不显示路线【英文标题】:Google Maps not showing route 【发布时间】:2016-08-16 06:14:48 【问题描述】:

我正在尝试显示两个标记之间的路线,但地图始终只显示爱尔兰的默认位置并且没有显示路线

public string DrawMapDirections(string Start,string End,string[] WayPoints)

    string map = "<script type=\"text/javascript\" src=\"https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false\"></script>" +
    "<script>" +
        "var rendererOptions =  "+ 
            "draggable: true "+
        "; " +
        "var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); " +
        " var directionsService = new google.maps.DirectionsService(); " +
        " var map; " +

        "function initialize()  " +
            "var ireland = new google.maps.LatLng(53.085222, -7.558594); " + //Default Ireland
            " var mapOptions =  " +
            " zoom: 7, " +
            " mapTypeId: google.maps.MapTypeId.ROADMAP," +
            " center: ireland " +
            "; " +
            "map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); " +
            "directionsDisplay.setMap(map); " +
            "directionsDisplay.setPanel(document.getElementById('directionsPanel'));" +

            "google.maps.event.addListener(directionsDisplay, 'directions_changed', function()  " +
                "computeTotalDistance(directionsDisplay.directions); "+
            "); "+ 
            //Call calcRoute
            " calcRoute();" +
        "" +

        "function calcRoute()  " +
            "var start = '" + Start.Replace("'", "") + "'; " +
            "var end = '" + End.Replace("'", "") + "'; " +
            "var waypts = []; ";

    foreach (string s in WayPoints)
    
        map += "waypts.push( " +
                "location:'" + s.Replace("'","") + "'); ";
    
            map += "var request =  " +
                "origin: start, " +
                "destination: end, " +
                "waypoints: waypts, " +
                "optimizeWaypoints: document.getElementById('chkOptimizeWaypoints').checked, " +
                "durationInTraffic:document.getElementById('chkDurationInTraffic').checked , " +
                "provideRouteAlternatives: document.getElementById('chkProvideRouteAlternatives').checked," +
                "avoidHighways: document.getElementById('chkAvoidHighWays').checked," +
                "avoidTolls: document.getElementById('chkAvoidTolls').checked, " + 
                "travelMode: google.maps.DirectionsTravelMode.DRIVING " +
            "; " +
            "directionsService.route(request, function(response, status)  " +
                "if (status == google.maps.DirectionsStatus.OK) " +
                    "directionsDisplay.setDirections(response);" +
                    "var route = response.routes[0];" +
              "" +
            ");" +
         " " +

         "function computeTotalDistance(result)  "+ 
            "var total = 0; "+
            "var myroute = result.routes[0]; " +
            "for (i = 0; i < myroute.legs.length; i++)  "+
                "total += myroute.legs[i].distance.value; "+
            " "+ 
            "total = total / 1000; "+ 
            "document.getElementById('total').innerhtml = total + ' km'; "+
        " "+

         "</script>";
    return map;

起点和终点通过这个函数传递:

GoogleMap gm = new GoogleMap();
html += gm.DrawMapDirections(start, end, waypoints.ToArray());

例如,起点可能是 - Treloggan Ind Est, Newquay, TR7 2SX, Cornwall, UNITED KINGDOM。

我没有收到任何错误,所以我不知道为什么它不显示路线

好的,这是地图返回的内容:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var rendererOptions =  draggable: true ; 
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);  
var directionsService = new google.maps.DirectionsService();  
var map; function initialize()  
    var ireland = new google.maps.LatLng(53.085222, -7.558594);  
    var mapOptions =   zoom: 7,  mapTypeId: google.maps.MapTypeId.ROADMAP, center: ireland ; 
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); 
    directionsDisplay.setMap(map); 
    directionsDisplay.setPanel(document.getElementById('directionsPanel'));
    google.maps.event.addListener(directionsDisplay, 'directions_changed', 

        function()  
            computeTotalDistance(directionsDisplay.directions); 
        );  
        calcRoute()
    ;
    function calcRoute()  
    var start = 'Unit 2, Hendy Industrial Estate, Hendy, SWANSEA, SA4 0XP, West Glamorgan, UNITED KINGDOM'; 
    var end = 'Treloggan Ind Est, Newquay, TR7 2SX, Cornwall, UNITED KINGDOM'; 
    var waypts = []; 
    var request =  
    origin: start, destination: end, 
    waypoints: waypts, optimizeWaypoints: document.getElementById('chkOptimizeWaypoints').checked, 
    durationInTraffic:document.getElementById('chkDurationInTraffic').checked , 
    provideRouteAlternatives: document.getElementById('chkProvideRouteAlternatives').checked,
    avoidHighways: document.getElementById('chkAvoidHighWays').checked,avoidTolls: document.getElementById('chkAvoidTolls').checked, 
    travelMode: google.maps.DirectionsTravelMode.DRIVING ; 
    directionsService.route(request, function(response, status)  
        if (status == google.maps.DirectionsStatus.OK)
            directionsDisplay.setDirections(response);var route = response.routes[0];); 
        
        function computeTotalDistance(result)  
            var total = 0; 
            var myroute = result.routes[0]; 
            for (i = 0; i < myroute.legs.length; i++)  
                total += myroute.legs[i].distance.value;  
                total = total / 1000; 
                document.getElementById('total').innerHTML = total + ' km'; 
         
    </script>

【问题讨论】:

你能发布实际输出而不是服务器代码吗?此外,如果路由不成功,请在代码中放置一个错误处理程序 - 您应该会收到一条错误消息 你能发布你的aspx页面内容吗? @Kyle 我将输出发布到问题 【参考方案1】:

请试试我的 aspx 代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Search Route Direction</title>  

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>  

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">  
    </script>  

    <%--Getting User Current Location--%>  

    <script type="text/javascript">  
        if (navigator.geolocation)   
            navigator.geolocation.getCurrentPosition(success);  
         else   
            alert("There is Some Problem on your current browser to get Geo Location!");  
          

        function success(position)   
            var lat = position.coords.latitude;  
            var long = position.coords.longitude;  
            var city = position.coords.locality;  
            var LatLng = new google.maps.LatLng(lat, long);  
            var mapOptions =   
                center: LatLng,  
                zoom: 12,  
                mapTypeId: google.maps.MapTypeId.ROADMAP  
            ;  

            var map = new google.maps.Map(document.getElementById("MyMapLOC"), mapOptions);  
            var marker = new google.maps.Marker(  
                position: LatLng,  
                title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: "  
                            + lat + +"<br />Longitude: " + long  
            );  

            marker.setMap(map);  
            var getInfoWindow = new google.maps.InfoWindow( content: "<b>Your Current Location</b><br/> Latitude:" +  
                                    lat + "<br /> Longitude:" + long + ""  
            );  
            getInfoWindow.open(map, marker);  
          
    </script>  

    <%--Getting Route Direction From User Current Location to Destination--%>  

    <script type="text/javascript">  
        function SearchRoute()   
            document.getElementById("MyMapLOC").style.display = 'none';  

            var markers = new Array();  
            var myLatLng;  

            //Find the current location of the user.  
            if (navigator.geolocation)   
                navigator.geolocation.getCurrentPosition(function(p)   
                    var myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);  
                    var m = ;  
                    m.title = "Your Current Location";  
                    m.lat = p.coords.latitude;  
                    m.lng = p.coords.longitude;  
                    markers.push(m);  

                    //Find Destination address location.  
                    var address = document.getElementById("txtDestination").value;  
                    var geocoder = new google.maps.Geocoder();  
                    geocoder.geocode( 'address': address , function(results, status)   
                        if (status == google.maps.GeocoderStatus.OK)   
                            m = ;  
                            m.title = address;  
                            m.lat = results[0].geometry.location.lat();  
                            m.lng = results[0].geometry.location.lng();  
                            markers.push(m);  
                            var mapOptions =   
                                center: myLatLng,  
                                zoom: 4,  
                                mapTypeId: google.maps.MapTypeId.ROADMAP  
                            ;  
                            var map = new google.maps.Map(document.getElementById("MapRoute"), mapOptions);  
                            var infoWindow = new google.maps.InfoWindow();  
                            var lat_lng = new Array();  
                            var latlngbounds = new google.maps.LatLngBounds();  

                            for (i = 0; i < markers.length; i++)   
                                var data = markers[i];  
                                var myLatlng = new google.maps.LatLng(data.lat, data.lng);  
                                lat_lng.push(myLatlng);  
                                var marker = new google.maps.Marker(  
                                    position: myLatlng,  
                                    map: map,  
                                    title: data.title  
                                );  
                                latlngbounds.extend(marker.position);  
                                (function(marker, data)   
                                    google.maps.event.addListener(marker, "click", function(e)   
                                        infoWindow.setContent(data.title);  
                                        infoWindow.open(map, marker);  
                                    );  
                                )(marker, data);  
                              
                            map.setCenter(latlngbounds.getCenter());  
                            map.fitBounds(latlngbounds);  

                            //***********ROUTING****************//  

                            //Initialize the Path Array.  
                            var path = new google.maps.MVCArray();  

                            //Getting the Direction Service.  
                            var service = new google.maps.DirectionsService();  

                            //Set the Path Stroke Color.  
                            var poly = new google.maps.Polyline( map: map, strokeColor: '#4986E7' );  

                            //Loop and Draw Path Route between the Points on MAP.  
                            for (var i = 0; i < lat_lng.length; i++)   
                                if ((i + 1) < lat_lng.length)   
                                    var src = lat_lng[i];  
                                    var des = lat_lng[i + 1];  
                                    path.push(src);  
                                    poly.setPath(path);  
                                    service.route(  
                                        origin: src,  
                                        destination: des,  
                                        travelMode: google.maps.DirectionsTravelMode.DRIVING  
                                    , function(result, status)   
                                        if (status == google.maps.DirectionsStatus.OK)   
                                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++)   
                                                path.push(result.routes[0].overview_path[i]);  
                                              
                                         else   
                                            alert("Invalid location.");  
                                            window.location.href = window.location.href;  
                                          
                                    );  
                                  
                              
                         else   
                            alert("Request failed.")  
                          
                    );  

                );  
              
            else   
                alert('Some Problem in getting Geo Location.');  
                return;  
              
          
    </script>  

</head>  
<body>  
    <form id="form1" runat="server">  
    <table style="border: solid 15px blue; width: 100%; vertical-align: central;">  
        <tr>  
            <td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; background-color: skyblue;  
                text-align: center; font-family: Verdana; font-size: 20pt; color: Green;">  
                Draw Route Between User's Current Location & Destination On Google Map  
            </td>  
        </tr>  
        <tr>  
            <td style="background-color: skyblue; text-align: center; font-family: Verdana; font-size: 14pt;  
                color: red;">  
                <b>Enter Destination:</b>  
                <input type="text" id="txtDestination" value="" style="width: 200px" />  
                <input type="button" value="Search Route" onclick="SearchRoute()" />  
            </td>  
        </tr>  
        <tr>  
            <td>  
                <div id="MyMapLOC" style="width: 550px; height: 470px">  
                </div>  
                <div id="MapRoute" style="width: 500px; height: 500px">  
                </div>  
            </td>  
        </tr>  
    </form>  
</body>  
</html> 

【讨论】:

【参考方案2】:

您的代码在我看来是正确的。我使用您的代码创建了一个 sn-p,并从路由请求中返回了“未找到”状态。如果我将起点更改为 Google 地图可以找到的地址,则会显示路线(在下面的 sn-p 中)。

如果您知道起点的纬度和经度,则可以使用它,否则您将需要一个方向服务知道的地址。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Direction Service Example</title>
</head>

<body>
  <div id="map_canvas" style="width: 600px;height: 600px"></div>
  <script>
    var map;
    var directionsDisplay;
    var directionsService;

    function initialize() 
      var ireland = new google.maps.LatLng(53.085222, -7.558594);
      var mapOptions = 
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: ireland
      ;
      directionsDisplay = new google.maps.DirectionsRenderer(
        draggable: true
      );
      directionsService = new google.maps.DirectionsService();
      map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
      directionsDisplay.setMap(map);
      directionsDisplay.setPanel(document.getElementById('directionsPanel'));
      google.maps.event.addListener(directionsDisplay, 'directions_changed',

        function() 
          computeTotalDistance(directionsDisplay.directions);
        );
      calcRoute();
    

    function calcRoute() 
      var start = 'Hendy Industrial Estate, Hendy, Pontarddulais, Swansea, Carmarthenshire SA4 0XP, UK';
      var end = 'Treloggan Ind Est, Newquay, TR7 2SX, Cornwall, UNITED KINGDOM';
      var waypts = [];
      var request = 
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: false,
        durationInTraffic: true,
        provideRouteAlternatives: true,
        avoidHighways: false,
        avoidTolls: false,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      ;
      directionsService.route(request, function(response, status) 
        if (status == google.maps.DirectionsStatus.OK) 
          directionsDisplay.setDirections(response);
          var route = response.routes[0];
        
      );
    

    function computeTotalDistance(result) 
      var total = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) 
        total += myroute.legs[i].distance.value;
      
      total = total / 1000;
      document.getElementById('total').innerHTML = total + ' km';
    
  </script>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
</body>

</html>

【讨论】:

以上是关于谷歌地图不显示路线的主要内容,如果未能解决你的问题,请参考以下文章

如何删除不相关的道路并在谷歌地图中显示所需的路线?对应的API是啥?

谷歌地图与黑莓路线

用谷歌地图规划路线[关闭]

如何在谷歌地图上画线

谷歌地图 - 将嵌入移动到静态

谷歌地图 - 如何找出用户的位置并在 Swift 中显示从该位置到目的地点的路线?