how to draw polylines on google maps dynamically

前端 未结 1 1623
栀梦
栀梦 2021-01-15 04:44

I cant able to draw polylines on google maps. am getting the value dynamically.

var flightPlanCoordinates=[];
n = \"new google.maps.LatLng(\";
q = \")\";
var         


        
相关标签:
1条回答
  • 2021-01-15 05:25

    You are creating an array of strings ("new google.maps.LatLng(coor1,coord2)"), not an array of google.maps.LatLng objects.

    This works for me.

    var r=['13.034056,80.250489|13.036324,80.248538|13.026394,80.237562'];
    var coordinates = r[0].split("|");
    var flightPlanCoordinates = new Array();
    for(i=0;i<coordinates.length;i++)
    {  
      var point =new google.maps.LatLng(coordinates[i].split(',')[0],coordinates[i].split(',')[1]);
      flightPlanCoordinates.push(point);   
    }   
    
    
    var flightPath = new google.maps.Polyline({
     path: flightPlanCoordinates,
     geodesic: true,
     strokeColor: '#FF0000',
     strokeOpacity: 1.0,
     strokeWeight: 2
     });
    
    flightPath.setMap(map);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    

    working example

    code snippet:

    function initialize() {
      var mapOptions = {
        zoom: 3,
        center: new google.maps.LatLng(0, -180),
        mapTypeId: google.maps.MapTypeId.TERRAIN
      };
    
      var map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
    
    var r=['13.034056,80.250489|13.036324,80.248538|13.026394,80.237562'];
    var coordinates = r[0].split("|");
    var flightPlanCoordinates = new Array();
    var bounds = new google.maps.LatLngBounds();
    for(i=0;i<coordinates.length;i++)
    {  
      var point =new google.maps.LatLng(coordinates[i].split(',')[0],coordinates[i].split(',')[1]);
      bounds.extend(point);
      flightPlanCoordinates.push(point);   
    }   
    
    
    var flightPath = new google.maps.Polyline({
     path: flightPlanCoordinates,
     geodesic: true,
     strokeColor: '#FF0000',
     strokeOpacity: 1.0,
     strokeWeight: 2
     });
    
    flightPath.setMap(map);
    map.fitBounds(bounds);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    html, body, #map-canvas {
            height: 100%;
            margin: 0px;
            padding: 0px
          }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="map-canvas"></div>

    0 讨论(0)
提交回复
热议问题