javascript - 将文字添加到gmap标记

时间:2012-09-08 10:45:14

标签: google-maps

我使用gmap进行地理定位,即在特定位置的Google地图上设置标记。 现在我想要实现的是设置标记,一旦用户点击其中一个标记,就会打开一个信息窗口并显示特定文本。每个标记都有自己的文本。

现在问题是我无法确定用户点击了哪个标记,因此无法设置正确的文字。

以下是代码段:

    //**Global variables**/
    var thingsOfInterest = new Array(new Array(), new Array(),new Array());
    var map = null;
    //End Global variables

    //init google map

function initGoogleMaps(){
    map = new google.maps.Map(document.getElementById("map_canvas"));
    var centerMap = new google.maps.LatLng(48.337881,14.320323);
    $('#map_canvas').gmap({'zoom':7,'center': centerMap});
    $('#map_canvas').gmap('option', 'zoom', 10);

   //This is not working on my ios-simulator, no idea why. Anyway....
   forge.geolocation.getCurrentPosition(function(position) {
            alert("Your current position is: "+position);
         }, function(error) {
    });
}
/*End init map*/

/*Set the markers on the map*/
function setMarkers() {
    /* thingsOf Interest contains:
     * thingsOfInterest[i][0] -> the text that the marker should hold
     * thingsOfInterest[i][1] -> the latitude
     * thingsOfInterest[i][2] -> the longitude
     */

    for (var i = 0; i < thingsOfInterest.length; i++) { //Iterate through all things
      var item = thingsOfInterest[i];  //get thing out of array
      var itemLatLng = new google.maps.LatLng(item[1], item[2]);  

      $('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2]) } ).click(function(e) {
                    $('#map_canvas').gmap('openInfoWindow', {'content': 'dummyContent'}, this); ///////SET REAL CONTENT HERE
      });
    }

}

现在这一切都很棒,但我想念的是获取用户在函数() - eventHandler中点击的标记。如果我能得到特定的标记,我可以在上面设置文本。

我希望这很清楚。

非常感谢任何帮助。

谢谢,

enne

1 个答案:

答案 0 :(得分:1)

假设您的代码虚拟文字正在运行,您可以立即传递您的文字..

$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2])})
   .click(function(e) {
      $('#map_canvas').gmap('openInfoWindow', {'content': item[0]}, this); 
   });

或者另一种方法是:

function setMarkers() {

    for (var i = 0; i < thingsOfInterest.length; i++) {

        var item = thingsOfInterest[i];  
        var itemLatLng = new google.maps.LatLng(item[1], item[2]);

        var marker = new google.maps.Marker({ position: itemLatLng, map: map });

        google.maps.event.addListener(marker, 'click', function () {
            var infowindow = new google.maps.InfoWindow({ content: item[0] });
            infowindow.open(map, marker);
        });
    }
}
相关问题