Search code examples
javascripthtmlopenlayersopenlayers-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. This is my Javascript script and the small portion of Html, can anyone please explain me ho to achieve this with an example?

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>

The above code is working very well as I'm able to display markers correctly on the map.


Solution

  • Below is a code snippet that creates a popup (InfoWindow) for markers, displaying the name property of the feature.

    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:

    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>