简体   繁体   English

没有nodejs的Openlayers 6标记弹出窗口?

[英]Openlayers 6 marker popup without nodejs?

I'm a newbie with openlayers and a bit confused on their nodejs style, for my reasons I can't use nodejs and I'm struggling on how to find some good documentation for achieving my goal without the use of NodejS, basically I need to click on a marker and get a popup related to the marker to appear for showing some info about that marker like city name and population number, all those info are given to me by a jSon received from the server.我是openlayers的新手,对他们的nodejs风格有点困惑,因为我的原因我不能使用nodejs,我正在努力寻找一些好的文档来实现我的目标而不使用NodejS,基本上我需要单击标记并获得与标记相关的弹出窗口以显示有关该标记的一些信息,例如城市名称和人口数量,所有这些信息都是由从服务器收到的 jSon 提供给我的。 This is my Javascript script and the small portion of Html, can anyone please explain me ho to achieve this with an example?这是我的 Javascript 脚本和 Html 的一小部分,任何人都可以用一个例子来解释一下吗?

HTML HTML

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

JAVASCRIPT 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>

The above code is working very well as I'm able to display markers correctly on the map.上面的代码运行良好,因为我能够在 map 上正确显示标记。

Below is a code snippet that creates a popup (InfoWindow) for markers, displaying the name property of the feature.下面是一个代码片段,它为标记创建一个弹出窗口(信息窗口),显示特征的name属性。

working example 工作示例

The code that creates the popup and opens it:创建弹出窗口并打开它的代码:

/**
 * 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";
  }
});

Based on the following example:基于以下示例:

结果地图的屏幕截图

 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