折线谷歌地图

时间:2016-12-20 15:06:59

标签: javascript google-maps

无法弄清楚我的代码出错的地方。想要地图上的标记,单击它时会显示城市名称。想要一条连接标记的线。有什么想法吗?

var line = new google.maps.Polyline({
    path: [
        new google.maps.LatLng(37.4419, -122.1419), 
        new google.maps.LatLng(37.4519, -122.1519)
    ],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
map: map
});

var locations = [
  ['Dalian', 38.914003, 121.614682]
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 5,
  center: new google.maps.LatLng(45.141789, 124.825118),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    title: locations[i][0]
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

1 个答案:

答案 0 :(得分:0)

  1. 您在定义地图之前定义折线。折线的map属性需要是有效的地图对象,如果您在地图之后定义它,则更容易做到这一点。

  2. 您的折线位于加利福尼亚州帕洛阿尔托,地图以中国为中心。

  3. 您的问题中只有一个标记,您不能使用一个点制作折线。

  4. fiddle

    代码段

    function initialize() {
    
      var locations = [
        ['Dalian', 38.914003, 121.614682]
      ];
    
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 1,
        center: new google.maps.LatLng(45.141789, 124.825118),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      var line = new google.maps.Polyline({
        path: [
          new google.maps.LatLng(37.4419, -122.1419),
          new google.maps.LatLng(37.4519, -122.1519)
        ],
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 10,
        map: map
      });
    
      var infowindow = new google.maps.InfoWindow();
    
      var marker, i;
    
      for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(locations[i][1], locations[i][2]),
          map: map,
          title: locations[i][0]
        });
    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
          }
        })(marker, i));
      }
    }
    google.maps.event.addDomListener(window, "load", initialize);
    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>