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

时间:2016-03-15 23:18:15

标签: javascript google-maps google-maps-api-3

我是新的使用谷歌地图,我想画多条路线,彼此分开,这一切都好,画我的标记OK,但路线总是画线没有道路,我的代码,画线路:

  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++;                
        }

输入数据:

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

但总是画这条线:

how to remove those lines

如何删除这些行?

2 个答案:

答案 0 :(得分:2)

目前,您将所有结果串在一条折线中。路线服务是异步的,结果可能会以不同于发送的顺序返回。一种解决方案是使每个独立方向成为单独的折线。如果您需要将它们组合成一条折线,您需要跟踪订单并按正确的顺序将它们组合在一起。

proof of concept fiddle

代码段

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>

答案 1 :(得分:0)

将此代码放入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);

将此代码放在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>