最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - draw different route line between multiple markers maps - Stack Overflow

programmeradmin3浏览0评论

I'm new using google maps, I want draw multiple route, separated from one another, this point all OK, paint my markers OK, but the route always draw lines where there is no road, my code, that draw route:

  for (var t = 0; t < lat_lng.length; t++) {
        var path = new google.maps.MVCArray();

        //Intialize the Direction Service
        var service = new google.maps.DirectionsService();
       var directionsDisplay = new google.maps.DirectionsRenderer();
        //Set the Path Stroke Color
        var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
            if ((t + 1) < lat_lng.length) {
                var src = lat_lng[t];
                var des = lat_lng[t + 1];                   
                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 k = 0, len = result.routes[0].overview_path.length; k < len; k++) {
                            path.push(result.routes[0].overview_path[k]);

                        }
                    }
                });
            }

            t++;                
        }

Input data:

"lat": '19.449045', "lng": '-99.1588115', "latdest": '19.54951', "lngdest": '-99.20688', "lat": '19.4219738', "lng": '-99.0992125', "latdest": '19.446199', "lngdest": '-99.1609357',

but always paint this lines:

How to remove those lines?

I'm new using google maps, I want draw multiple route, separated from one another, this point all OK, paint my markers OK, but the route always draw lines where there is no road, my code, that draw route:

  for (var t = 0; t < lat_lng.length; t++) {
        var path = new google.maps.MVCArray();

        //Intialize the Direction Service
        var service = new google.maps.DirectionsService();
       var directionsDisplay = new google.maps.DirectionsRenderer();
        //Set the Path Stroke Color
        var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
            if ((t + 1) < lat_lng.length) {
                var src = lat_lng[t];
                var des = lat_lng[t + 1];                   
                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 k = 0, len = result.routes[0].overview_path.length; k < len; k++) {
                            path.push(result.routes[0].overview_path[k]);

                        }
                    }
                });
            }

            t++;                
        }

Input data:

"lat": '19.449045', "lng": '-99.1588115', "latdest": '19.54951', "lngdest": '-99.20688', "lat": '19.4219738', "lng": '-99.0992125', "latdest": '19.446199', "lngdest": '-99.1609357',

but always paint this lines:

How to remove those lines?

Share Improve this question edited Mar 16, 2016 at 0:27 geocodezip 161k14 gold badges226 silver badges254 bronze badges asked Mar 15, 2016 at 23:18 Diego CortésDiego Cortés 1011 gold badge1 silver badge5 bronze badges 1
  • sorry my Coordinates: "lat": '19.449045', "lng": '-99.1588115', "latdest": '19.54951', "lngdest": '-99.20688', "lat": '19.4219738', "lng": '-99.0992125', "latdest": '19.446199', "lngdest": '-99.1609357', – Diego Cortés Commented Mar 15, 2016 at 23:20
Add a ment  | 

2 Answers 2

Reset to default 3

Currently you are stringing all the results together in a single polyline. The directions service is asynchronous, the results may e back in a different order than sent. One solution is to make each independent directions result a separate polyline. If you need them bined into a single polyline, you need to keep track of the order and put them together in the correct order.

  • related question: Inconsistent behaviour drawing a route between two points in Google Maps v3
  • related question: Remove straight line in google map path using javascript

proof of concept fiddle

code snippet:

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var lat_lng = [
    new google.maps.LatLng(19.449045, -99.1588115),
    new google.maps.LatLng(19.54951, -99.20688),
    new google.maps.LatLng(19.4219738, -99.0992125),
    new google.maps.LatLng(19.446199, -99.1609357),
    new google.maps.LatLng(19.54578,-99.206918),
    new google.maps.LatLng(19.503391,-99.201939)

  ];
  for (var t = 0;
    (t + 1) < lat_lng.length; t++) {
    //Intialize the Direction Service
    var service = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();

    var bounds = new google.maps.LatLngBounds();
    if ((t + 1) < lat_lng.length) {
      var src = lat_lng[t];
      var des = lat_lng[t + 1];
      service.route({
        origin: src,
        destination: des,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      }, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          // new path for the next result
          var path = new google.maps.MVCArray();
          //Set the Path Stroke Color
          // new polyline for the next result
          var poly = new google.maps.Polyline({
            map: map,
            strokeColor: '#4986E7'
          });
          poly.setPath(path);
          for (var k = 0, len = result.routes[0].overview_path.length; k < len; k++) {
            path.push(result.routes[0].overview_path[k]);
            bounds.extend(result.routes[0].overview_path[k]);
            map.fitBounds(bounds);
          }
        } else alert("Directions Service failed:" + status);
      });
    }
  }
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis./maps/api/js"></script>
<div id="map_canvas"></div>

put this code in c#

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MvCon"].ToString());
SqlDataAdapter da;
DataTable dt = new DataTable();
ArrayList marker = new ArrayList();
public string[] myArray;

        da = new SqlDataAdapter("select * from table_name", con);
        da.Fill(dt);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            marker.Add("{ " + '"' + "lat" + '"' + ": " + '"' + dt.Rows[i]["latitude"] + '"' + ", " + '"' + "lng" + '"' + ": " + '"' + dt.Rows[i]["longitude"] + '"' + " }");
        }
        myArray = (string[])marker.ToArray(typeof(string));
        hdn_loc.Value = "[" + string.Join(",", myArray) + "]";
        this.ClientScript.RegisterStartupScript(this.GetType(), "script", "map_location();", true);

put this code in aspx page inside body tag

<script type="text/javascript">
    function map_location() {           
        var marker_point = document.getElementById('<%= hdn_loc.ClientID %>').value;
        var markers = JSON.parse(marker_point);//converts string value in array
        //alert(markers.slice(-1)[0].lng) // last index value
        var myOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), myOptions);       
        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) {

                    // for getting values of array  
                    var loc;
                    var latlng = new google.maps.LatLng(data.lat, data.lng);

                    var geocoder = geocoder = new google.maps.Geocoder();
                    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[1]) {

                                loc = "Location: " + results[1].formatted_address;
                                infoWindow.setContent(loc);
                                infoWindow.open(map, marker);
                            }

                        }

                    })


                });
            })
            (marker, data);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        for (var t = 0;
          (t + 1) < lat_lng.length; t++) {
            //Intialize the Direction Service
            var service = new google.maps.DirectionsService();
            var directionsDisplay = new google.maps.DirectionsRenderer();

            var bounds = new google.maps.LatLngBounds();
            if ((t + 1) < lat_lng.length) {
                var src = lat_lng[t];
                var des = lat_lng[t + 1];
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        // new path for the next result
                        var path = new google.maps.MVCArray();
                        //Set the Path Stroke Color
                        // new polyline for the next result
                        var poly = new google.maps.Polyline({
                            map: map,
                            strokeColor: '#4986E7',
                        });
                        poly.setPath(path);
                        for (var k = 0, len = result.routes[0].overview_path.length; k < len; k++) {
                            path.push(result.routes[0].overview_path[k]);
                            bounds.extend(result.routes[0].overview_path[k]);
                            map.fitBounds(bounds);
                        }
                    } else alert("Directions Service failed:" + status);
                });
            }
        }
    }   
</script>

<asp:HiddenField runat="server" ID="hdn_loc" />
<asp:Button runat="server" ID="btn" Text="show loc" OnClick="btn_Click" />
<div id="dvMap" style="width: 500px; height: 400px"></div>
发布评论

评论列表(0)

  1. 暂无评论