簡體   English   中英

沒有nodejs的Openlayers 6標記彈出窗口?

[英]Openlayers 6 marker popup without nodejs?

我是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>

上面的代碼運行良好,因為我能夠在 map 上正確顯示標記。

下面是一個代碼片段,它為標記創建一個彈出窗口(信息窗口),顯示特征的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";
  }
});

基於以下示例:

結果地圖的屏幕截圖

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM