2016-09-16 61 views
-2

我已经使用Google地图Api构建了一个Web应用程序,并获得了多段线点击事件的问题。 我试图给地图添加一些标记,然后将它们加在一起。我希望如果我点击多段线,我可以得到作为该多段线起点和终点的标记。但是,只有一个返回结果相同同为所有时间我点击不同polylines.Here我的源代码:多个Google地图多段线点击事件

var locations = [ 
    { title: "Site 1", lat: 16.044137, lng: 108.206511 }, 
    { title: "Site 2", lat: 16.067161, lng: 108.186259 }, 
    { title: "Site 3", lat: 16.063472, lng: 108.215248 }, 
    { title: "Site 4", lat: 16.041847, lng: 108.193539 }, 
    { title: "Site 5", lat: 16.054186, lng: 108.172890 }, 
]; 

var map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 14, 
    center: new google.maps.LatLng(16.067161, 108.186259), 
    mapTypeId: google.maps.MapTypeId.SATELLITE 
}); 

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

var polyLineClicked = function (polyline, fromIndex, toIndex) { 
    google.maps.event.addListener(polyline, 'click', function (e) { 
     infowindow.setContent = fromIndex + " to " + toIndex; 
     infowindow.setPosition = event.latLng; 
     infowindow.open(map); 
    }); 
} 
for (var i = 0; i < locations.length; i++) { 
    var position = new google.maps.LatLng(locations[i].lat, locations[i].lng); 
    var marker = new google.maps.Marker({ 
     position: position, 
     map: map 
    }); 

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

    if (i <= locations.length - 2) { 

     var nextPosition = new google.maps.LatLng(locations[i + 1].lat, locations[i + 1].lng); 
     var polyline = new google.maps.Polyline({ 
      path: [position, nextPosition], 
      strokeColor: 'black', 
      strokeOpacity: 1, 
      strokeWeight: 7, 
      map: map, 
      fromPositionIndex: i, 
      toPositionIndex: i+1 
     }); 
     var fromIndex = locations[i].title; 
     var toIndex = locations[i + 1].title; 

     polyLineClicked(polyline, fromIndex, toIndex); 
    } 
} 
+0

张贴的代码不能正常工作(不显示任何信息窗口) – geocodezip

回答

1

在你polyLineClicked功能,你重新分配setContent和setPosition两种,而不是调用infoWindow class methods

var polyLineClicked = function(polyline, fromIndex, toIndex) { 
    google.maps.event.addListener(polyline, 'click', function(e) { 
    // call the methods instead of reassigning 
    infowindow.setContent(fromIndex + " to " + toIndex); 
    infowindow.setPosition(e.latLng); 
    infowindow.open(map); 
    }); 
}; 

jsfiddle

+0

太棒了!非常感谢。 –

+0

如果您发现答案帮助了您,请立即加入! – kaskader