Openlayers 6标记弹出不用nodejs?

问题描述 投票:0回答:1

我是openlayers的新手,对他们的nodejs风格有点困惑,由于我的原因,我不能使用nodejs,我正在努力寻找一些好的文档来实现我的目标,而不使用NodejS,基本上我需要点击一个标记,并得到一个与该标记相关的弹出窗口,以显示该标记的一些信息,如城市名称和人口数量,所有这些信息都是通过从服务器接收的jSon给我的。这是我的Javascript脚本和小部分的Html,谁能给我解释一下如何用一个例子来实现?

HTML

<div id="mapdiv" style="height: 500px;width: 100%;"><div id="popup"></div></div>

JAVASCRIPT

<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
    @Scripts.Render("~/Scripts/jquery-3.3.1.js");
    <script>
        var jsonObject = { "coords": [] };
        $.ajax({
            url: '@Url.Action("GetPlaces", "Place")',   //Indirizzo controller.
            type: 'GET',
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var descr = data[i].descrizione;
                    var coord = data[i];
                    //var coordObj = JSON.stringify(coord);
                    jsonObject['coords'].push(coord);
                }
                //var temp = JSON.stringify(data);
                //geojsonObject = JSON.parse(data);
            },
            async: false
        });


        const features = [];

        for (const coord of jsonObject.coords) {
            features.push(new ol.Feature({
                geometry: new ol.geom.Point(
                    ol.proj.fromLonLat([coord.longitude, coord.latitude]),
                    'XY'
                )
            }));
        }

        const style = new ol.style.Style({
            image: new ol.style.Icon({

                    anchor: [0.5, 0.5],
                    size: [2400, 2400],
                    offset: [52, 0],
                    opacity: 1,
                    scale: 0.012,
                src: "http://localhost:22950/Assets/pin-png-39460.png"
            })
        });

        const vectorSource = new ol.source.Vector({
            features
        });

        const vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style
        });

        const map = new ol.Map({
            target: 'mapdiv',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                }),
                vectorLayer
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([45.32, 8.41]),
                zoom: 3
            })
        });
    </script>

上面的代码非常好用,因为我能够在地图上正确地显示标记,我是openlayers的新手,对他们的nodejs风格有点困惑,由于我不会使用nodejs的原因,我正在努力寻找一些好的文档来实现我的目标。

javascript html openlayers openlayers-6
1个回答
1
投票

下面是一个代码片段,为标记创建一个弹出式(InfoWindow),显示的是 name 特性的属性。

工作实例

创建弹窗并打开它的代码。

/**
 * Elements that make up the popup.
 */
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');

/**
 * Add a click handler to hide the popup.
 * @return {boolean} Don't follow the href.
 */
closer.onclick = function() {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

/**
 * Create an overlay to anchor the popup to the map.
 */
var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});

/**
* Add a click handler to the map to render the popup.
*/
map.on('singleclick', function(evt) {
  var name = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
    return feature.get('name');
  })
  if (name) {
    container.style.display="block";
    var coordinate = evt.coordinate;
    content.innerHTML = name;
    overlay.setPosition(coordinate);
  } else {
    container.style.display="none";
  }
});

基于下面的例子:

screenshot of resulting map

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, "green"],
  ['Coogee Beach', -33.923036, 151.259052, "blue"],
  ['Cronulla Beach', -34.028249, 151.157507, "yellow"],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, "purple"],
  ['Maroubra Beach', -33.950198, 151.259302, "red"]
];


/**
 * Elements that make up the popup.
 */
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');


/**
 * Add a click handler to hide the popup.
 * @return {boolean} Don't follow the href.
 */
closer.onclick = function() {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};


/**
 * Create an overlay to anchor the popup to the map.
 */
var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});


var features = [];
for (var i = 0; i < locations.length; i++) {
  features.push(coloredSvgMarker([locations[i][2], locations[i][1]], locations[i][0], locations[i][3]));
}


var vectorSource = new ol.source.Vector({ // VectorSource({
  features: features
});

var vectorLayer = new ol.layer.Vector({ // VectorLayer({
  source: vectorSource
});

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({ // TileLayer({
      source: new ol.source.OSM()
    }), vectorLayer
  ],
  overlays: [overlay],
  target: 'map',
  view: new ol.View({
    center: ol.proj.fromLonLat([-0.12755, 51.507222]),
    zoom: 10
  })
});

// make the map's view to zoom and pan enough to display all the points
map.getView().fit(vectorSource.getExtent(), map.getSize());

/**
 * Add a click handler to the map to render the popup.
 */
map.on('singleclick', function(evt) {
  var name = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
    return feature.get('name');
  })
  if (name) {
    container.style.display = "block";
    var coordinate = evt.coordinate;
    content.innerHTML = name;
    overlay.setPosition(coordinate);
  } else {
    container.style.display = "none";
  }
});
map.on('pointermove', function(evt) {
  map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel) ? 'pointer' : '';
});


function coloredSvgMarker(lonLat, name, color, circleFill) {
  if (!color) color = 'red';
  if (!circleFill) circleFill = 'white';
  var feature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat(lonLat)),
    name: name
  });
  var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 30 30" enable-background="new 0 0 30 30" xml:space="preserve">' +
    '<path fill="' + color + '" d="M22.906,10.438c0,4.367-6.281,14.312-7.906,17.031c-1.719-2.75-7.906-12.665-7.906-17.031S10.634,2.531,15,2.531S22.906,6.071,22.906,10.438z"/>' +
    '<circle fill="' + circleFill + '" cx="15" cy="10.677" r="3.291"/></svg>';

  feature.setStyle(
    new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 1.0],
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        src: 'data:image/svg+xml,' + escape(svg),
        scale: 2,
        imgSize: [30, 30],
      })
    })
  );
  return feature;
}
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 100%;
  width: 100%;
}

.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 80px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: "x";
}
<link rel="stylesheet" href="https://openlayers.org/en/v6.3.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v6.3.0/build/ol.js" type="text/javascript"></script>
<div id="map" class="map"></div>
<div id="popup" class="ol-popup">
  <a href="#" id="popup-closer" class="ol-popup-closer"></a>
  <div id="popup-content"></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.