1

我有一个 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));
    }

任何帮助深表感谢 :)

4

1 回答 1

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));
}
于 2013-04-16T19:46:37.343 回答