简体   繁体   中英

draw different route line between multiple markers maps

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?

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

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.com/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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM