DEVHIDE
  • Home (current)
  • About
  • Contact
  • Cookie
  • Home (current)
  • About
  • Contact
  • Cookie
  • Disclaimer
  • Privacy
  • TOS
Login Or Sign up

Change openlayer popup based on specific feature clicked

76 Views Asked by warrenjb At 19 October 2023 at 17:45 2025-12-13T02:26:05.713000

My .html:

<div id="map"></div>
<div id="popup" class="ol-popup">
  <a href="#" id="popup-closer" class="ol-popup-closer"></a>
  <div id="popup-content"></div>
</div>

My .js

var attribution = new ol.control.Attribution({
  collapsible: false
});
var map = new ol.Map({
  controls: ol.control.defaults({ attribution: false }).extend([attribution]),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM({
        //url: 'https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png'
      })
    })
  ],
  target: 'map',
  view: new ol.View({
    //Center map to producing office address
    center: ol.proj.fromLonLat([-76, 45]),
    zoom: 2.75
  })
});

var CircleStyle = ol.style.Circle
var {Fill, Icon, Stroke, Style} = ol.style;
var styles = {
  'greenCircle': new Style({
    image: new CircleStyle({
      radius: 7,
      stroke: new Stroke({
        color: 'green',
        width: 5,
      }),
    }),
  }),
  'yellowCircle': new Style({
    image: new CircleStyle({
      radius: 7,
      stroke: new Stroke({
        color: 'yellow',
        width: 5,
      }),
    }),
  }),
  'redCircle': new Style({
    image: new CircleStyle({
      radius: 7,
      stroke: new Stroke({
        color: 'red',
        width: 5,
      }),
    }),
  }),
};

var Can = new ol.Feature({
  type: 'greenCircle',
  geometry: new ol.geom.Point(ol.proj.fromLonLat([-79, 44]))
  , id: 1
});
var Ger = new ol.Feature({
  type: 'yellowCircle',
  geometry: new ol.geom.Point(ol.proj.fromLonLat([13, 53]))
  , id: 2
});
var Chn = new ol.Feature({
  type: 'redCircle',
  geometry: new ol.geom.Point(ol.proj.fromLonLat([116, 40]))
  , id: 3
});
var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [Can, Ger, Chn]
  }),
  style: function (feature) {
    return styles[feature.get('type')];
  }
});
map.addLayer(layer);

var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});
map.addOverlay(overlay);

closer.onclick = function () {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

map.on('singleclick', function (event) {
  if (map.hasFeatureAtPixel(event.pixel) === true) {
    var coordinate = event.coordinate;
    content.innerHTML = '<b style="color:black;">Canada:</b><br/><a href="program.html#Canada" style="color:blue;">Policy Details</a><br/><a href="service.html" style="color:blue;">Service Details</a>';
    overlay.setPosition(coordinate);
  } else {
    overlay.setPosition(undefined);
    closer.blur();
  }
});

The above code successfully shows three different colored circles on a map and the same popup for each when the user clicks on the circles. The problem is I want to show different popups for each circle when the user clicks on them. I am using Openlayers 5. Appreciate any help. Thanks!

openlayers-5
Original Q&A
1

There are 1 best solutions below

0
Mike Mike On 19 October 2023 at 18:49 BEST ANSWER

You will need to determine which feature is at the clicked pixel, and display content based on the properties of that feature:

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v5.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/v5.3.0/build/ol.js"></script>
    <style>
      .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: 280px;
      }
      .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: "✖";
      }
    </style>

  </head>
  <body>
    <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>
    <script>

var attribution = new ol.control.Attribution({
  collapsible: false
});
var map = new ol.Map({
  controls: ol.control.defaults({ attribution: false }).extend([attribution]),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM({
        //url: 'https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png'
      })
    })
  ],
  target: 'map',
  view: new ol.View({
    //Center map to producing office address
    center: ol.proj.fromLonLat([-76, 45]),
    zoom: 2.75
  })
});

var CircleStyle = ol.style.Circle
var {Fill, Icon, Stroke, Style} = ol.style;
var styles = {
  'greenCircle': new Style({
    image: new CircleStyle({
      radius: 7,
      stroke: new Stroke({
        color: 'green',
        width: 5,
      }),
    }),
  }),
  'yellowCircle': new Style({
    image: new CircleStyle({
      radius: 7,
      stroke: new Stroke({
        color: 'yellow',
        width: 5,
      }),
    }),
  }),
  'redCircle': new Style({
    image: new CircleStyle({
      radius: 7,
      stroke: new Stroke({
        color: 'red',
        width: 5,
      }),
    }),
  }),
};

var Can = new ol.Feature({
  type: 'greenCircle',
  geometry: new ol.geom.Point(ol.proj.fromLonLat([-79, 44]))
  , id: 1
});
var Ger = new ol.Feature({
  type: 'yellowCircle',
  geometry: new ol.geom.Point(ol.proj.fromLonLat([13, 53]))
  , id: 2
});
var Chn = new ol.Feature({
  type: 'redCircle',
  geometry: new ol.geom.Point(ol.proj.fromLonLat([116, 40]))
  , id: 3
});
var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [Can, Ger, Chn]
  }),
  style: function (feature) {
    return styles[feature.get('type')];
  }
});
map.addLayer(layer);

var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});
map.addOverlay(overlay);

closer.onclick = function () {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

map.on('singleclick', function (event) {
  var feature = map.forEachFeatureAtPixel(event.pixel,
    function(feature) {
      return feature;
    },
    {hitTolerance: 5}
  );
  if (feature) {
    var coordinate = feature.getGeometry().getCoordinates();
    var style = layer.getStyleFunction()(feature);
    content.innerHTML = '<b style="color:' + style.getImage().getStroke().getColor()  + ';background:lightgray;">'  + feature.get('type') + '</b>';
    overlay.setPosition(coordinate);
  } else {
    overlay.setPosition(undefined);
    closer.blur();
  }
});

    </script>
  </body>
</html>

Related Questions in OPENLAYERS-5

  • Openlayers Pbf vector tiles bad performance
  • Change openlayer popup based on specific feature clicked
  • Openlayers XYZ not supporting different tileSizes for the same map instance, 512 and 256
  • How to move the text to top left instead of the bottom left corner in a openlayers feature?
  • openlayers 5.2.0. Markers with text
  • what add marker to map openlayer 5 with angular 6
  • Get style of KML feature in OL5
  • Geodestic measures in OL 5?
  • How to show count in heatmap instead of magnitude?
  • In openlayers multiple markers at same lat and long not showing all markers
  • OpenLayers 5 loads the WFS features but doesn't add and show them in the map
  • Openlayers map tiles are not initially loaded in single page app
  • How to update an XYZ layer in Open Layers 5
  • OpenLayers v 5.3.0 - get back attribution behavior
  • how to get style from layer in geoserver

Trending Questions

  • UIImageView Frame Doesn't Reflect Constraints
  • Is it possible to use adb commands to click on a view by finding its ID?
  • How to create a new web character symbol recognizable by html/javascript?
  • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
  • Heap Gives Page Fault
  • Connect ffmpeg to Visual Studio 2008
  • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
  • How to avoid default initialization of objects in std::vector?
  • second argument of the command line arguments in a format other than char** argv or char* argv[]
  • How to improve efficiency of algorithm which generates next lexicographic permutation?
  • Navigating to the another actvity app getting crash in android
  • How to read the particular message format in android and store in sqlite database?
  • Resetting inventory status after order is cancelled
  • Efficiently compute powers of X in SSE/AVX
  • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

Popular # Hahtags

javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

Popular Questions

  • How do I undo the most recent local commits in Git?
  • How can I remove a specific item from an array in JavaScript?
  • How do I delete a Git branch locally and remotely?
  • Find all files containing a specific text (string) on Linux?
  • How do I revert a Git repository to a previous commit?
  • How do I create an HTML button that acts like a link?
  • How do I check out a remote Git branch?
  • How do I force "git pull" to overwrite local files?
  • How do I list all files of a directory?
  • How to check whether a string contains a substring in JavaScript?
  • How do I redirect to another webpage?
  • How can I iterate over rows in a Pandas DataFrame?
  • How do I convert a String to an int in Java?
  • Does Python have a string 'contains' substring method?
  • How do I check if a string contains a specific word?
.

Copyright © 2021 Jogjafile Inc.

  • Disclaimer
  • Privacy
  • TOS
  • Homegardensmart
  • Math
  • Aftereffectstemplates