谷歌地图javascript绘制折线

时间:2016-02-04 23:51:10

标签: javascript google-maps

我正在尝试通过Google地图绘制折线。我已经通过捕捉到道路功能获得了一条路径,但我把它作为一个对象,但我需要一个数组作为路径。知道如何将路径对象转换为数组?这是我到目前为止的代码:

<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">
      html, body { height: 100%; margin: 0; padding: 0; }
      #map { height: 100%; }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script type="text/javascript">
    var map;

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 65, lng: -20},
          zoom: 8
        });
        path = (64.06507, -21.57787),(64.06324000000001, -21.567200000000003),(64.06213000000001, -21.560760000000002),(64.06129, -21.555650000000004),(64.06070000000001, -21.55158);
        var geralinu = new google.maps.Polyline({
            path: path,
            strokeColor: 'Red',
            strokeOpacity: 1.0,
            strokeWeight: 2
        });
        //geralinu.setPath(lina);
        }
    </script>
    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyClRZNMxcuO2BSi3nynNQu7e7uFyzylWZ4&callback=initMap">
    </script>
  </body>
</html>

我得到的错误是Uncaught TypeError:Object.entries不是函数

1 个答案:

答案 0 :(得分:0)

这不是有效的javascript:

path = (64.06507, -21.57787),(64.06324000000001, -21.567200000000003),(64.06213000000001, -21.560760000000002),(64.06129, -21.555650000000004),(64.06070000000001, -21.55158);

我建议制作一组google.maps.LatLngLiteral个对象(我最后删除了一些额外的零):

var path = [{lat: 64.06507,lng: -21.57787}, {lat: 64.06324,lng: -21.5672}, {lat: 64.06213,lng: -21.56076}, {  lat: 64.06129,lng: -21.55565}, {lat: 64.0607,lng: -21.55158}];

proof of concept fiddle

代码段

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 65,
      lng: -20
    },
    zoom: 8
  });
  var path = [{lat: 64.06507,lng: -21.57787}, 
              {lat: 64.06324,lng: -21.5672},
              {lat: 64.06213,lng: -21.56076}, 
              {lat: 64.06129,lng: -21.55565}, 
              {lat: 64.0607,lng: -21.55158}];
  
  var geralinu = new google.maps.Polyline({
    path: path,
    strokeColor: 'Red',
    strokeOpacity: 1.0,
    strokeWeight: 2,
    map: map
  });
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < geralinu.getPath().getLength(); i++) {
    bounds.extend(geralinu.getPath().getAt(i));
  }
  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>