Modify the output string using the `ol.control.MouseControl` function

I need to modify the output text within the target attribute of ol.control.MouseControl (version 3.15.1 of openlayers). Currently, the code only displays longitude and latitude values, but I want to include the strings "long" and "lat" before each value. For example, it should read as lat: 12.543, long: 14.567. How can I achieve this?

var regStyle = new ol.style.Style({
    fill: new ol.style.Fill({
        color: 'rgba(127,129,112,0.1)'
    }),
    stroke: new ol.style.Stroke({
        color: 'green',
        width: 2
    })
});

var reg = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: 'http://localhost:8080/Project_first/assets/geojson/regioni.geojson',
        format: new ol.format.GeoJSON(),
        projection: 'EPSG:3857'
    }),
    style: regStyle
});

var prov = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: 'http://localhost:8080/Project_first/assets/kml/province.kml',
        format: new ol.format.KML(),
        projection: 'EPSG:3857'
    })
});

var base_layer = new ol.layer.Tile({
    source: new ol.source.OSM()
}); 

var italy = ol.proj.fromLonLat([14.334, 40.965]);

var view = new ol.View({
    center: italy,
    zoom: 6
});

var scale = new ol.control.ScaleLine({
    className: 'ol-scale-line',
    target: document.getElementById('scale-line')
});

var mousePositionControl = new ol.control.MousePosition({
    coordinateFormat: ol.coordinate.createStringXY(2),
    projection: 'EPSG:3857',
    className: 'custom-mouse-position',
    target: document.getElementById('mouse-position'),
    undefinedHTML: ' '
});

var map = new ol.Map({
    controls: ol.control.defaults({
        attributionOptions: {collapsible: false}
    }).extend([mousePositionControl, scale]),
    target: 'map',
    layers: [base_layer, prov, reg],
    view: view
});

function initMap() {
    // do map object creation and initialization here
    // ...

    // add a click event handler to the map object
    GEvent.addListener(map, "click", function(overlay, latLng) {
        // display the lat/lng in your form's lat/lng fields
        document.getElementById("lat").value = latLng.lat();
        document.getElementById("lng").value = latLng.lng();
    });
}

Answer №1

If you need to customize the coordinate display, you can use the following function:

function customCoordFormat(fraction) {
  var template = 'Coordinates: {x} | {y}';
  return (
    function(coords) {
        return ol.coordinate.format(coords, template, fraction);
    });
}

Then, simply input this function into the coordinateFormat parameter when creating a new instance of ol.control.MousePosition:

var mousePosControl = new ol.control.MousePosition({
  coordinateFormat: customCoordFormat(2),
  projection: 'EPSG:4326',
  className: 'custom-mouse-pos',
  target: document.getElementById('mouse-pos'),
  undefinedHTML: ' '
});

For an example, visit http://jsfiddle.net/jonataswalker/qchbpawm/.

Answer №2

Here is a working solution:

function formatCoordinates(precision) {
  var template = 'Coordinate is: {x} | {y}';
  return (
    function(coordinate) {
        var formattedCoordinates = ol.coordinate.format(coordinate, template, precision);
        console.log( 'formattedCoordinates='+ formattedCoordinates);
        return
    });
}

var mousePositionControl = new ol.control.MousePosition({
    coordinateFormat: formatCoordinates(6), // ol.coordinate.createStringXY(6), 
    projection: 'EPSG:4326',
    className: 'custom-mouse-position',
    target: document.getElementById('mapCoDiv'), //   'latitude'
    undefinedHTML: ' '
});

2) There is still the question of how to use the render function :

    var assignCoordinates = function(e) {

        var coordinates = e. ????? 
        var latitude, longitude = coordinates.split(',');
        console.log( 'latitude='+ latitude +',   longitude='+ longitude ); 
        $('#'+this.latEl).val(latitude);
        $('#'+this.longEl).val(longitude);    
    }; 


   var mousePositionControl = new ol.control.MousePosition({
        // will disable this function coordinateFormat: formatCoord(6), // ol.coordinate.createStringXY(6), 
        projection: 'EPSG:4326',
        render : assignCoordinates,
        className: 'custom-mouse-position',
        target: document.getElementById('mapCoDiv'), //   'latitude'
        undefinedHTML: ' '

    });

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

What is the best way to change the date format from "yyyy-MM-dd" in a JavaScript file to "dd/MM/yyyy" and "MM/dd/yyyy" formats in an HTML file?

Is there a way to transform the date string "2020-08-02" from a JavaScript file into the formats "08/02/2020" and "02/08/2020" in an html file, without relying on the new Date() function in JavaScript? I would greatly appreciate any assistance with this t ...

Setting input type to date with full width using jQuery Mobile

Currently working on a web project utilizing jQuery Mobile 1.1.1 and looking to incorporate a <input type="date" /> that spans the entire width of the page. However, encountering a peculiar issue (noticing a gap where an arrow should be displayed) sp ...

Unable to display the "detailed form" on the next page pagination of the DataTables

Every time I click on the class="detail" button, the detail-form displays perfectly. However, after clicking on the datatable paging to go to the next page (next record of datatable), the detail-form does not show up. I attempted to change the datatables c ...

What is the best way to use ajax for uploading multiple images at once?

I'm having trouble uploading multiple image files. Can someone please review my code? <form id="fileupload" method="POST" enctype="multipart/form-data"> <input type="file" name="files[]" multiple="multiple" id="images_input"> & ...

Stop the interval when the variable equals "x"

I've created a function that controls a specific row in my database using AJAX. The function is triggered by a click event and placed within a setInterval function to check ten times per second. Initially, it will return 0, but eventually (usually wi ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

Launch the database-connected gallery in a lightbox interface

Having a small issue here - attempting to create an anchor tag labeled "Photos" that, when clicked by the user, triggers Ajax to retrieve results from a PHP/MySQL database and display images within a lightbox. This is what I have attempted so far: <a ...

Preventing a timer from pausing in NextJS during periods of inactivity

Recently, I developed a straightforward timer application using Next.js that should continue counting even when the browser window is inactive. However, I noticed that if I switch to another window for approximately 5 minutes, the timer stops counting whi ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

Using JavaScript in MVC4 to implement JSon

Looking to integrate JavaScript into my project... I have data stored in a database...... Retrieving it using LinQ as shown below public List<SelectListItem> getTokens() { var tokens = from T in db.tokens select T; List<Selec ...

Why isn't the background-image : url() function cooperating in TypeScript?

I am facing an issue in my Rails project where I am trying to toggle the visibility of an image when a user clicks on it. Below is the code snippet I have implemented: $(document).ready(function() { if ($("#myvideo").prop('muted', true)){ ...

The image being displayed is significantly wider than the corresponding HTML element

I'm attempting to display this webpage in PNG format using npm's wkhtmltox: <!doctype html> <html> <head> <meta charset="utf-8"> <style> html, body { padding: 0; width: 340px; } ...

Integrating new features into the bison/jison calculator programming language

Looking to enhance the functionality of the Jison calculator example by introducing some basic functions. As someone new to parsing and bison/jison, here's a glimpse of my progress so far: /* lexical grammar */ %lex %{ var funcs = { pow: funct ...

Set the value of a variable to the result of a JavaScript function

I recently wrote a function that retrieves JSON data from a specified URL. Here's what the function looks like: function getJSON(url) { request.get({ url: url, json: true, headers: { 'User-Agent': 'request&a ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Ways to initiate a flip motion

Looking for a way to create a flip image effect when clicked by the user. Here is the code I have so far: let img = document.querySelector('img') let div; let click = 0; img.onclick=function(){ console.log(click) if(click %2 ==0){ d ...

What is the best way to loop back to the beginning of an array after reaching the last element in JavaScript?

I have an array in JavaScript containing music notes: const musicNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B&apos ...

Adding picture to table using JavaScript

I am currently developing a Web application using the Play Framework technology. In one of my scala.html views, I have successfully displayed an image with the following code: <img src="@routes.Assets.at("images/image/1003.png")" width="30" height="30" ...