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

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

"Transforming the Website Background with a Splash of Color

I am trying to figure out how to change the color scheme of my website with a button click. Currently, when I select a different color, only the background of the webpage I'm on changes, not the entire website. I have applied CSS but it's not ref ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

Error: The "checkAvailability" method is not available in the model object

When attempting to implement some functionality methods for my model, I encountered an issue where sending a request resulted in the following traceback: /home/nano/Dev/JS/OMI/node_modules/mongoose/lib/utils.js:413 throw err; ^ TypeE ...

The functionality of the document download button using Express.js and node.js appears to be malfunctioning

For my current project, I am aiming to enable users to effortlessly download a document by simply clicking on a designated button. Project Outline: public/client.js console.log('Client-side code running'); const button = document.get ...

Having difficulty integrating a Hangout button using APIs on my webpage

I'm having some trouble adding a basic Hangout button component to initiate Google's Hangout. I've been following the steps outlined on the Google Developer page, but despite my efforts, I can't seem to resolve the following issue: Fai ...

Are there any methods to implement object-oriented programming in JavaScript?

The concept of prototype-based object-oriented programming in JavaScript is intriguing, but there are many scenarios where the need for class-based object creation arises. Consider a vector drawing application, where the workspace begins empty and you can ...

Creating a new session in Node.js for every request

Our team is currently developing a nodejs application that requires the maintenance of sessions. We have implemented express to handle node variables, but we are facing an issue where a new session is created every time we hit a new service. The structure ...

Python script for extracting content from web pages that are loaded dynamically

I am facing an issue with extracting content from a webpage on my website. Despite trying to use selenium and clicking buttons, I have not been successful. #!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox import ...

Is it possible to use JavaScript or jQuery to call a WCF Service and retrieve a collection of System.IO.Stream objects?

I am developing a WCF service that will be utilized by plain JavaScript on the client side, as well as some jQuery JavaScript. 1) How can I set up the plain client JavaScript to call the WCF Service in a manner that retrieves a collection of System.IO.Str ...

Implementing HTML content inside an el-select component in Vue.js using Element UI

I am working with a dropdown feature that has various options: var Main = { data() { return { drawer: { form: { period: null } }, data : [ { label: "JAN to MAR 2021", value: " ...

Utilize Jquery to extract HTML content from an array of links and implement regular expressions

Currently, I am embarking on the journey of developing a Google Chrome extension despite my limited experience in this field. My aim is to create a tool that can identify individuals who have left reviews on Amazon products. Specifically, I am looking to l ...

Generating a random number within a JSON field: A guide

I need help generating a random number for the Corelation Id field in my JSON. I tried using the function ${__Random(1, 10000)} but it's not working. Any suggestions on how to achieve this? "LoginRequest": { "Header": { ...

Can the keydown event have an impact on setInterval functionality?

I created a basic snake game using JavaScript and attempted to incorporate a new feature where var trail = []; var tail = 5; var normal_speed = 1000 / 10 var speed = 1000 / 10; var game_status = 0; var my_game; button.addEventListener("click", function ...

Sending data from configuration to factory in AngularJS and UI Router

Trying to perform a search in an http call with a dynamic value based on the current view. The factory setup is as follows: .factory('SearchService', ['$http','$filter', function($http, $filter) { var service = { get ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

How is it that connecting an event listener to a React child component can be done in a way that resembles simply passing a prop

class Board extends React.Component { constructor(props) { super(props); this.state = { squares: Array(9).fill(null), }; } handleClick(i) { // do things } render() { return ( <div ...

Is it Feasible to Have Angular 1.4 View Encapsulation and Shadow DOM Integration?

Currently, I am in the process of transitioning my app from Polymer to Angular 1.4 due to stability concerns. Given my experience with Polymer and web components, as well as the future integration of Angular 2, I have decided to structure my app using the ...

Error: Unable to access the 'file' property of an undefined object

As I attempt to upload an image from my HTML and upon clicking the save button, I invoke an upload function within the controller. However, when I enter the upload function in the controller, I encounter issues accessing the $scope to verify the $scope.fil ...

Nested ng-repeat in AngularJS by numeric value

Looking to create a sliding carousel layout for displaying a bunch of data with 8 points per slide. The desired structure is as follows: Slide datapoint 1 datapoint 2 datapoint 3 datapoint 4 datapoint 5 datapoint 6 datapoint 7 ...