OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below:

const map = new OpenLayers.Map("basicMap");

const mapnik = new OpenLayers.Layer.OSM();

const fromProjection = new OpenLayers.Projection("EPSG:4326");

// Transform from WGS 1984
const toProjection = new OpenLayers.Projection("EPSG:900913");

// to Spherical Mercator Projection
const position = new OpenLayers.LonLat(13.41,52.52).transform(fromProjection, toProjection);

const zoom = 15;

map.addLayer(mapnik);
map.setCenter(position, zoom );

const markers = new OpenLayers.Layer.Markers( "Markers" );

map.addLayer(markers);

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control,
{
    defaultHandlerOptions:
    {
        'single': true,
        'double': true,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false
    },

    initialize: function(options)
    {
        this.handlerOptions = OpenLayers.Util.extend({},this.defaultHandlerOptions);

        OpenLayers.Control.prototype.initialize.apply(this, arguments);

        this.handler = new OpenLayers.Handler.Click(this, {'click': this.trigger}, this.handlerOptions);
    },

    trigger: function(e)
    {
        const lonlat = map.getLonLatFromViewPortPx(e.xy);

        alert("clicked");

        alert("Lat, Lon : " + lonlat.lat + ", " + lonlat.lng);

        markers.addMarker(new OpenLayers.Marker(lonlat));
    },

    touchstart: function(e)
    {
        console.log();
    },

    touchend: function(e)
    {
        console.log();
    },

    handleSingle: function(e)
    {
        console.log();
    }
});

const control = new OpenLayers.Control.Click();
map.addControl(control);
control.activate();

However, after conducting some tests, I noticed that the message "clicked" was not being displayed even though there were no errors in the console and the map was loading correctly.

Is there something incorrect in the above code? How can this issue be resolved?

Note: The Ionic framework is being used for this implementation.

Any assistance would be greatly appreciated.

Thank you.

Answer №1

OpenLayers.Map does not trigger a click event.

To enable click functionality in OpenLayers 2, you need to define a custom "Click" control. Here is an example implementation (source: ):

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
    defaultHandlerOptions: {
        'single': true,
        'double': false,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false
    },
    initialize: function(options) {
        this.handlerOptions = OpenLayers.Util.extend(
            {}, this.defaultHandlerOptions
        );
        OpenLayers.Control.prototype.initialize.apply(
            this, arguments
        ); 
        this.handler = new OpenLayers.Handler.Click(
            this, {
                'click': this.trigger
            }, this.handlerOptions
        );
    }, 
    trigger: function(e) {
        var lonlat = map.getLonLatFromPixel(e.xy);
        alert("You clicked near " + lonlat.lat + " N, " +
                                  + lonlat.lon + " E");
    }
});

Customize the trigger function with your desired logic or actions before using the control in your code:

var control = new OpenLayers.Control.Click();
map.addControl(control);
control.activate();

Further details on click handler options can be found here:

For instance, if you want to handle double clicks, simply set the double property to true accordingly.

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

Utilizing Multiple Canvases Simultaneously

I'm facing an issue where I need to crop multiple images on a single page using the canvas tag in HTML5 along with JavaScript. However, only one image is displaying on the page. How can I resolve this? The code snippet that I have attempted is provid ...

Tips for creating a new terminal window and interacting with it?

I have a node server that generates logs of activities in the terminal. To have more control over the server during runtime, I aim to integrate a repl server within it. However, I need to ensure that the logs and repl server do not interfere with each ot ...

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

Enhance your file uploading capabilities with Protractor and dropzonejs

I'm new to using protractor and I have a project that involves testing with Angular and dropzonejs for file uploads. Although I've come across some information on how to upload files with protractor, I am struggling to figure out how to do so wit ...

Storing information in a database using Phantomjs

My app is built on phantomjs and here's how it currently operates: 1. A php script retrieves data from my postgres database as an array, 2. The array of data is then passed as an argument to a shell_exec command running a phantomjs script, 3. Phantomj ...

"Changing background color, incorporating hover effects, utilizing !important, and manipulating .css properties with

Encountered a dilemma. I devised a "tabs" feature illustrated in the following demo: http://jsfiddle.net/4FLCe/ The original intention was for the tab to change color to A when hovered over, and to color B when clicked on. However, as shown in the demo, ...

The table refuses to load

I've been troubleshooting this issue for the past two days. The array is visible in the console, but it refuses to show up on the table. I've tried multiple approaches, but none seem to work. I suspect that "tobodyHtml" is not defined properly, a ...

Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user se ...

No data found in php://input when accessing Azure

Having an issue with posting a complex JSON object to my Azure IIS server running PHP 5.4 using AngularJS: var request = $http({ method: "post", url: "/php/mail.php", data: $scope.contactForm, headers: { 'Content-Type': & ...

Avoiding duplication of prints in EJS template files

In my EJS code, I have created a loop to fetch the total amount of items from the database. Here is my current code: <h2>Summary</h2> <% if(typeof items.cart!=="undefined"){ var amount = 0; %> <% i ...

Utilizing angular.forEach in $scope to extract data from an array

I am working with a dynamically changing array based on another piece of code and I am attempting to extract specific data from it. Here is an example of one dynamically generated array stored in $scope.filtereditem: [{ "active": true, "createdAt": " ...

Updating a function in jQuery UI after dynamically loading content through AJAX

I've been on a quest for days now, searching high and low for an answer to my dilemma. While I've managed to solve most of the issues that arose after adding AJAX calls to my code, there's one piece that still eludes me. Just to provide som ...

Have Vue props been set to null?

Currently, I have a component within my vue.js application that looks like this: export default { props: ['forums'], methods: { increment(forum, index) { ForumService.increment(forum) .then(() => { ...

Saving a collection of unique identifiers in Firebase

Struggling to find a solution for organizing Firebase data: Each user has posts with generated IDs, but how do I store these IDs in a user node efficiently? Currently using string concatenation and treating them like a CSV file in my JS app, but that feel ...

I developed an RPG game with an interactive element using jQuery. One of the biggest challenges I'm facing is the random selection process for determining which hero will be targeted by the enemy bots during battles

Hello, this marks my debut on stack overflow with a question. I've created a game inspired by old school RPGs where players choose from three heroes based on the Marvel universe to battle one of three enemies. The problem I'm facing is that even ...

Is it possible to arrange two items in one column and the rest as columns in MaterialUI Grid?

I need help arranging my arrows in a MaterialUI grid where one points up and the other points down. How can I achieve this layout? Attached below is an image of my current setup and the desired outcome. Here is my code: <Paper className={classes.paper ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

Enhancing your website's design with dynamic CSS variables using JavaScript

Is there a way to update CSS variables specifically scoped under a certain CSS class (or even other complex CSS selectors) that are predefined in a stylesheet? This question extends beyond just CSS variables and includes other CSS properties as well, quest ...

A guide on declaring an Angular variable within a Blade template

I'm working on the following code snippet: <div ng-repeat='item in reddit.items'> and I want to assign an item attribute (@{{item.content}}) to Blade if certain conditions are met. @if(Auth::check() && !$this->ifFav(Auth::user()- ...