简体   繁体   English

在多个标记图之间绘制不同的路线

[英]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: 我是使用Google地图的新手,我想绘制多条路线,彼此分开,这一点一切正常,画好我的标记,但是路线总是在没有道路的地方绘制线,我的代码绘制路线:

  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# 将此代码放在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 将此代码放在body标签内的aspx页面中

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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