OpenLayers不让我添加Popup

时间:2014-10-17 01:22:38

标签: javascript openlayers openstreetmap

所以我有(或者有)OpenStreetMaps的工作版本,但现在我想在地图上添加弹出窗口,整个事情就破了。这是与弹出窗口问题有关的代码。疯狂的是,我复制并粘贴官方维基的代码,以便得到一个有效的例子。

function init() {

    map = new OpenLayers.Map( 'heatmapArea');

    var query = new OpenLayers.LonLat(-122.2928337167, 37.5549570333).transform(
                  new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    var popup = new OpenLayers.Popup.FramedCloud("Popup", query, null, "Text", null, true);
    map.addPopup(popup, false);

    var lat = 39.3138895;
    var lon = -98.2233523;
    var zoom = 4;
    var position = new OpenLayers.LonLat(lon, lat).transform( EPSG_WGS84, EPSG_900913);
    map.setCenter(position, zoom );

}

我的浏览器控制台中出现的问题是:

errors

我删除了我认为与此问题无关的代码,但如果有必要,我可以提供更多代码。我已经广泛搜索了所有我发现在我访问的网站上工作的示例,但打破了我的地图,每个StackOverflow对其他人的回答似乎都适用于原始海报,但又一次打破我的地图。 / p>

这是我试图复制的网站之一:

http://www.rigacci.org/openlayers/other_examples/markers.html

我非常渴望解决这个问题,我们将非常感谢任何帮助。谢谢!

-C.J。

1 个答案:

答案 0 :(得分:1)

真正了解OL API的人能够正确解释这一点,但基本上,你的代码很好,但是你需要重新排序。在调用addPopup之前,需要添加地图图层并缩放到某个范围。我认为这是因为addPopup不需要它自己的显式层;它使用地图图层;因此,在尝试使用之前,您需要在地图上使用地图图层。这是有道理的,但我不确定为什么你还需要调用zoom / zoomToExtent函数。

这是一个小提琴,我试图尽可能保持你的代码不变:

http://jsfiddle.net/sifriday/u3j6h97d/3/

这是JS的一些评论:

function init() {

    var map = new OpenLayers.Map( 'heatmapArea');
    // Add a map layer before trying to use addPopup
    map.addLayer(new OpenLayers.Layer.OSM());

    // Call the zoom function before trying to use addPopup
    var lat = 39.3138895;
    var lon = -98.2233523;
    // I've changed the zoom to 1 so you can immediately see the popup in the small fiddle window
    var zoom = 1;
    var position = new OpenLayers.LonLat(lon, lat).transform(
        "EPSG_WGS84", "EPSG_900913"
    );
    map.setCenter(position, zoom);

    // Finally here's your addPopup code
    var query = new OpenLayers.LonLat(
        -122.2928337167, 37.5549570333
    ).transform(
        new OpenLayers.Projection("EPSG:4326"), 
        map.getProjectionObject()
    );
    var popup = new OpenLayers.Popup.FramedCloud(
        "Popup", 
        query,
        // I added a size to make it fit in the small fiddle window
        new OpenLayers.Size(100,100),
        "Text",
        null,
        true
    );
    map.addPopup(popup);
}