根据用户在 Openlayers 3 中的输入在地图上绘制图标

Plot icon on map, based on user's input in Openlayers 3

我们用最新的 Openlayers 3 地图升级了我们的应用程序。看起来 OL 3 使用完全不同的方法来比较他们在 OL 2 中使用的方法。在 JS 中不是很好。

我们希望用户能够在文本字段中输入坐标(经度、纬度),按下按钮,图标就会出现在地图上。反之亦然 - 当用户在地图上单击(单击)时,这些坐标(经度、纬度)应在这些文本字段上弹出,以便将来能够将其保存并更新到数据库中。

到目前为止,我能够显示地图,用户单击时会出现图标,并且完全无法了解如何获取坐标并将其显示到文本字段中。并且无法弄清楚如何让用户输入坐标并在该位置获取图标。到目前为止,这是我的代码:

html

  <div id="map" tabindex="0"></div>
<div id="txt">Click to add a marker!</div>
 <form>Lon:<input type="text" id="lon" name="lon">
  <br>Lat:<input type="text" id="lat" name="lat">
  <input type="button" id="get" onlclick = "getLocation" value="plot icon"></form>

这是 JS:

    var vectorSource = new ol.source.Vector(),
    vectorLayer = new ol.layer.Vector({
      source: vectorSource
    }),
    olview = new ol.View({
        center: [0, 0],
        zoom: 4,
        minZoom: 2,
        maxZoom: 20
    }),
    map = new ol.Map({
        target: document.getElementById('map'),
        view: olview,
        layers: [
            new ol.layer.Tile({
                style: 'Aerial',
                source: new ol.source.MapQuest({ layer: 'osm' })
            }),
            vectorLayer
        ]
    });


var iconStyle = new ol.style.Style({
    image: new ol.style.Icon({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: '//openlayers.org/en/v3.8.2/examples/data/icon.png'
    }),
    text: new ol.style.Text({
        font: '12px Calibri,sans-serif',
        fill: new ol.style.Fill({ color: '#000' }),
        stroke: new ol.style.Stroke({
            color: '#fff', width: 2
        }),
        text: 'lon and lat'
    })
});


map.on('click', function(evt){
    var feature = new ol.Feature(
        new ol.geom.Point(evt.coordinate)
    );
    feature.setStyle(iconStyle);
    vectorSource.clear();
    vectorSource.addFeature(feature);
    getLocation();
});
function getLocation() {
alert('how to get lon and lat ?!?'); }

您可以通过调用

获取点击坐标
evt.coordinate 

map.getEventCoordinate(evt.originalEvent);

所以在你的情况下它看起来像:

map.on('click', function(evt) {
  var coordinate1 = evt.coordinate;
  var coordinate2 = map.getEventCoordinate(evt.originalEvent);
  getLocation(coordinate1);
  getLocation(coordinate2);
});

function getLocation(coordinate) {
alert(coordinate);
}

要将标记添加到某个点,您可以按照以下示例进行操作: how to add markers with OpenLayers 3 (jsfiddle)

哪里

ol.geom.Point(ol.proj.transform([Math.random()*360-180, Math.random()*180-90], 'EPSG:4326',   'EPSG:3857')),

将是您想要的坐标,例如

ol.geom.Point(ol.proj.transform([0.5, 46], 'EPSG:4326',   'EPSG:3857')),
 map.on('click', function (evt) {


    var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:4326', 'EPSG:3857');
    var lon = lonlat[0];
    var lat = lonlat[1];}

为了长和lat你可以根据你的需要改变EPSG