OpenLayers不会在我的地图中添加标记

时间:2013-04-16 18:23:38

标签: javascript html openlayers

我有一个OpenLayers地图,我使用JavaScript函数创建它。然后我有一个按钮,当按下时调用另一个JavaScript函数,该函数具有向地图添加标记的代码。

由于某种原因,未添加标记。

OpenLayers地图创建代码:

function init()
    {
        var map, baseLayer;
        var options = {numZoomLevels: 5, isBaseLayer: true,};

        map = new OpenLayers.Map('map');            
        baseLayer = new OpenLayers.Layer.Image("My map","map.png", 
        new OpenLayers.Bounds(-2000, -2000, 1000, 1000),
        new OpenLayers.Size(1500,1500), options);
        map.addLayer(baseLayer);
        var center = new OpenLayers.LonLat(-100,-100);
        map.setCenter(center ,0);  
        map.addControl(new OpenLayers.Control.LayerSwitcher());
        map.addControl(new OpenLayers.Control.MousePosition());
        var size = new OpenLayers.Size(21,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
        var markers = new OpenLayers.Layer.Markers( "Marker" );
        map.addLayer(markers);
    }   

添加标记的代码:

function addMarker(x, y)
    {    
        markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(x, y),icon));
    }

非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:2)

这对我来说很好用:

var markers,icon;
function init(){
    var map, baseLayer;
    var options = {numZoomLevels: 5, isBaseLayer: true,};

    map = new OpenLayers.Map('map');            
    baseLayer = new OpenLayers.Layer.Image("My map","map.png", 
    new OpenLayers.Bounds(-2000, -2000, 1000, 1000),
    new OpenLayers.Size(1500,1500), options);
    map.addLayer(baseLayer);
    var center = new OpenLayers.LonLat(-100,-100);
    map.setCenter(center ,0);  
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.MousePosition());
    var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    //instance the icon
    icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
    //instance the marker layer
    markers = new OpenLayers.Layer.Markers( "Marker" );
    map.addLayer(markers);
}

function addMarker(x, y){    
    markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(x, y),icon));
}