在地图上绘制图标,基于用户's在Openlayers 3中的输入

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

本文关键字:Openlayers 输入 用户 绘制 地图 图标 于用户      更新时间:2023-09-26

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

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

到目前为止,我能够显示地图,在用户点击时显示图标,并完全专注于如何获取坐标并将其显示在文本字段中。并且不知道如何让用户输入坐标并获得该位置的图标。这是我到目前为止的代码:

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);
}

要将标记添加到某个点,可以按照以下示例操作:如何使用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];}

对于变长和变宽,您可以根据需要更改EPSG。