Карта загрузки OpenLayer с начальным маркером - PullRequest
0 голосов
/ 06 июля 2018

Я использую OpenLayer v4.6.5 для отображения карты на моей html-странице.Мне нужно показать маркеры на моей карте.Он отлично работает при нажатии на карту, но я не могу загрузить карту, на которой изначально отображается маркер.Почему последняя строка кода не имеет никакого эффекта?

<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>

<script>
function createMap(){
        var coordinate = someCoordinate;
        var vectorSource = new ol.source.Vector({});
        var vectorLayer = new ol.layer.Vector({ source: vectorSource });
        var view = new ol.View({ center: ol.proj.fromLonLat(coordinate), zoom: 12, maxZoom: 19, minZoom: 5 });
        var map = new ol.Map({
            layers: [new ol.layer.Tile({ source: new ol.source.OSM({ key: 'myKey', crossOrigin: '' }) }), vectorLayer,],
            target: document.getElementById(mapId),
            controls: ol.control.defaults(),
            view: view
        });

        // create custom marker image with custom text in bottom
        var iconStyle = new ol.style.Style({
            image: new ol.style.Icon({
                anchor: [12, 37],
                anchorXUnits: 'pixels', //'fraction'
                anchorYUnits: 'pixels',
                opacity: 0.8,
                src: 'marker.png'
            })
        });

        var marker;
        this.setMarker = function (coordinate) {
            marker = new ol.Feature(
                new ol.geom.Point(coordinate)
            );
            marker.setStyle(iconStyle);
            vectorSource.addFeature(marker);
        }

        map.on('click', function (evt) {
            setMarker(evt.coordinate);
        });

        return this;
}

var map = createMap();

// NOTE: This line of code has no effect!!!
map.setMarker(someCoordinate)

</script>

1 Ответ

0 голосов
/ 06 июля 2018

Вам нужно позвонить ol.proj.fromLonLat, чтобы преобразовать координаты в правильную проекцию (как вы это делали для центра карты):

this.setMarker = function (coordinate) {
  marker = new ol.Feature(
    new ol.geom.Point(ol.proj.fromLonLat(coordinate))
  );
  marker.setStyle(iconStyle);
  vectorSource.addFeature(marker);
}

подтверждение концепции связи

фрагмент кода:

var mapId = "map";

function createMap() {
  var coordinate = [-117.1610838, 32.715738];
  var vectorSource = new ol.source.Vector({});
  var vectorLayer = new ol.layer.Vector({
    source: vectorSource
  });
  var view = new ol.View({
    center: ol.proj.fromLonLat(coordinate),
    zoom: 12,
    maxZoom: 19,
    minZoom: 5
  });
  var map = new ol.Map({
    layers: [new ol.layer.Tile({
      source: new ol.source.OSM({
        key: 'myKey',
        crossOrigin: ''
      })
    }), vectorLayer, ],
    target: document.getElementById(mapId),
    controls: ol.control.defaults(),
    view: view
  });

  // create custom marker image with custom text in bottom
  var iconStyle = new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [12, 37],
      anchorXUnits: 'pixels', //'fraction'
      anchorYUnits: 'pixels',
      opacity: 0.8,
      src: 'https://maps.google.com/mapfiles/ms/micons/blue.png'
    })
  });

  var marker;
  this.setMarker = function(coordinate) {
    marker = new ol.Feature(
      new ol.geom.Point(ol.proj.fromLonLat(coordinate))
    );
    marker.setStyle(iconStyle);
    vectorSource.addFeature(marker);
  }
  return this;
}

var map = createMap();
map.setMarker([-117.1610838, 32.715738])
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 90%;
  width: 100%;
}
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<div id="map" class="map"></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...