"Utilizing OpenLayers to display markers coupled with interactive pop

I am struggling to implement a map with markers on my website. I want users to be able to click on these markers and view additional information, similar to how it works in Google Earth. Although I have the map and markers set up, I am having trouble getting the pop-up functionality to work.

Here is the JS code I have:

function initializeMap(){
    var northSeaLonLat = [4.25, 52.05];
    var centerWebMercator = ol.proj.fromLonLat(northSeaLonLat);

    var tileLayer = new ol.layer.Tile({ source: new ol.source.OSM() });
    markerLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [], projection: 'EPSG:3857' }) });

    var map = new ol.Map({
        controls: ol.control.defaults().extend([
            new ol.control.MousePosition({
                coordinateFormat: ol.coordinate.createStringXY(3),
                projection: 'EPSG:4326',
                undefinedHTML: ' ',
                className: 'custom-mouse-position',
                target: document.getElementById('custom-mouse-position'),
            })
        ]),
        layers: [tileLayer, markerLayer],
        target: 'map',
        view: new ol.View({
            projection: 'EPSG:3857',
            center: centerWebMercator,
            zoom: 7
        })
    });

    // Add marker
    var circle = new ol.style.Style({
        image: new ol.style.Circle({
            radius: 4,
            fill: new ol.style.Fill({
                color: 'rgba(200,0,0,0.9)',
            }),
            stroke: new ol.style.Stroke({
                color: 'rgba(100,0,0,0.9)',
                width: 2
            })
        })
    });

    coordinates = [[4.25, 52.05], [4.21, 52.01], [4.29, 52.29], [5.25, 52.05], [4.25, 51.05]];
    for (i = 0; i < coordinates.length; i++) { 
        var feature = new ol.Feature(
            new ol.geom.Point(ol.proj.transform(coordinates[i], 'EPSG:4326', 'EPSG:3857'))
        );
        feature.description = 'Coordinates: '+coordinates[i][0]+','+coordinates[i][1]+'\nBla';
        feature.setStyle(circle);
        markerLayer.getSource().addFeature(feature);
    }

    var element = document.getElementById('popup');
    var popup = new ol.Overlay({
      element: element,
      positioning: 'bottom-center',
      stopEvent: false
    });
    map.addOverlay(popup);

    // display popup on click
    map.on('click', function(evt) {
        var feature = map.forEachFeatureAtPixel(evt.pixel,
            function(feature, layer) {
                return feature;
            });
        if (feature) {
            popup.setPosition(evt.coordinate);
            $(element).popover({
                'placement': 'top',
                'html': true,
                'content': feature.get('description')
            });
            $(element).popover('show');
        } else {
            $(element).popover('destroy');
        }
    });
}

The code was sourced from an example on the website:

While it works there, I'm encountering difficulties making it work on my version. Any insights into why this might be happening?

Answer №1

popover does not come with OpenLayers software, but is a feature found in Bootstrap: http://getbootstrap.com/javascript/#popovers

For more information on overlays, you can check out the example provided by OpenLayers here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to add a string to a http get request in Angular

When a specific ID is typed into the input field, it will be saved as searchText: <form class="input-group" ng-submit="getMainData()"> <input type="text" class="form-control" ng-model="searchText" placeholder=" Type KvK-nummer and Press Enter" ...

SlickGrid checkbox formatter/editor experiencing issues with data consistency

Exploring the functionalities of SlickGrid'seditors/formatters, I delved into how these features could potentially alter the data object utilized for constructing the grid (as modifications within the table are usually reflected in the original data o ...

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

The collapse feature in react-bootstrap is malfunctioning

I've been experimenting with the Collapse feature from react-bootstrap in order to implement a collapsible table row. The goal is to have table rows that expand and collapse when clicked, revealing more information specific to that row. While it see ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...

Differences Between APP_INITIALIZER and platformBrowserDynamic with provide

I've discovered two different approaches for delaying an Angular bootstrap until a Promise or Observable is resolved. One method involves using APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: (configService: ConfigurationService) => ( ...

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

Hover over the image with some padding placed around it to see

I am struggling to figure out how to add padding to my image when hovering over it with Onmouseover. I have tried multiple solutions but none seem to be working. Here is the original code: <img src='/wp-content/uploads/2015/04/img-white.png' ...

How can JavaScript onClick function receive both the name and value?

My current challenge involves a function designed to disable a group of checkboxes if they are not checked. Originally, this function was set to work onClick(), with one argument being passed from the checkbox element. Now, I need this function to be trigg ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Ways to execute a function only once within setInterval

Hey there, I'm facing an issue with this... getSocketPerSecond = function () { Interval_PerSecond = setInterval(function () { $.ajax({ url: "/asset/ashx/GetSocket.ashx", type: "post", ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...

Mastering Generic Types in Functions in Typescript

My current structure looks like this: export interface Complex { getId<T>(entity: T): string } const test: Complex = { getId<Number>(entity){return "1"} // encountering an error 'entity is implicitly any' } I am wondering w ...

The instance cannot be accessed by ES6 class methods

Having trouble accessing the this instance in one of my methods within a class that I created. In my router, I am calling the method like this: import Emails from '../controllers/emails' import router from 'express' .... route.post(&a ...

Could you provide instructions on how to change mjs files into js format?

Is there a method to change .mjs files to .js files? Some hosting services do not yet support mjs files, so I am interested in converting them to js files. Context: Mozilla's PDFjs has incorporated JavaScript modules (mjs) into their code, but since ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

Exploring the Interaction of Users with HTML Table Cell <td>

I am currently analyzing the code for a web page. Within this code, users have the ability to double-click on a cell in a table (<td> as shown below) and input a value. Is there a specific attribute or element within this HTML that indicates user in ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

There was a problem encountered while trying to load the .json/.csv file

Attempting to grasp D3 through this video has been a challenging experience, particularly when attempting to load an external file. The code snippets are provided below: index.html <html> <head> <meta charset="utf-8"> <title& ...

How to avoid the need to wrap all setState calls with #act in React 18?

One issue I encountered was when upgrading from React 17 to 18, ReactDom render became asynchronous. To handle this, I needed to use #act to wrap the ReactDom render. However, React also required that all setState calls be wrapped with #act. If not done, ...