InfoWindow显示错误的地方

时间:2013-12-23 09:12:38

标签: javascript google-maps-api-3

我的网页没什么问题。当我试图在标记上显示InfoWindow时。窗口显示在地图的左上角而不是标记上。就像下面的屏幕一样: enter image description here

这是我用于放置标记和使用InfoWindows的脚本。

var infowindow;
function point(name, lat, long) {
    var self = this;
    self.name = name;
    self.lat = ko.observable(lat);
    self.long = ko.observable(long);

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, long),
    title: name,
    map: map,
    draggable: true
});

//if you need the poition while dragging
google.maps.event.addListener(marker, 'drag', function () {
    var pos = marker.getPosition();
    this.lat(pos.lat());
    this.long(pos.lng());
}.bind(this));

//if you just need to update it when the user is done dragging
google.maps.event.addListener(marker, 'dragend', function () {
    var pos = marker.getPosition();
    this.lat(pos.lat());
    this.long(pos.lng());
}.bind(this));

google.maps.event.addListener(marker, 'mouseover', function () {
    infowindow = new google.maps.InfoWindow({ content: "empty" });
    console.log(marker.title);
    infowindow.setContent(marker.name);
    infowindow.open(map, marker);

}.bind(this));


}

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

var viewModel = {
    points: ko.observableArray([
        new point('Test1', 55, 11),
        new point('Test2', 56, 12),
        new point('Test3', 57, 13)])

};
function addPoint() {
    viewModel.points.push(new point('a', 58, 14));
}

ko.applyBindings(viewModel);

这里全是jsfiddle:http://jsfiddle.net/24q8n/

2 个答案:

答案 0 :(得分:4)

您使用的marker.nameundefined。 因此,您正在为setContent分配未定义,显然会阻止infoWindow停止工作,最终会出现在左上角。 移除infowindow.setContent(marker.name)或将其替换为类似marker.title的值。或者在定义marker.name时定义var marker = ...

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, long),
    title: name,
    name: name, // define the name so setContent(marker.name) will work.
    map: map,
    draggable: true
});

或删除产生问题的行:

google.maps.event.addListener(marker, 'mouseover', function () {
    infowindow = new google.maps.InfoWindow({ content: "empty" });
    console.log(marker.title);
    // This line gives you the problem because marker.name is undefined.
    // infowindow.setContent(marker.name);
    infowindow.open(map, marker);    
}.bind(this)); 

答案 1 :(得分:2)

http://jsfiddle.net/upsidown/24q8n/1/

这是它的工作版本。

通常,信息窗口是您显示和隐藏更新内容的单个对象。您正在做的是在鼠标悬停监听器中重新创建InfoWindow对象。

而不是那样,只需在功能之外定义它:

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

然后就这样做:

infowindow.setContent(marker.title);
infowindow.open(map, marker);