Flyer: Move to Web Mercator coordinates (EPSG 3857) using panTo

I am currently using a standard leaflet map with a tile layer. In Leaflet, the only way to use the panTo method is by utilizing LatLng, for example,

map.panTo(new L.LatLng(40.17, -98.12));

However, I am wondering how I can use the panTo method if my coordinates are in EPSG:3857, such as (3679364.68,-9096106.74)?

In Openlayers, it is easy to work with a specific map projection, but Leaflet always requires latlng.

Is there a simple way to achieve this using the Leaflet library?

Thanks!

Answer №1

Utilizing Leaflet's panTo method by unprojecting a 3857 point is possible without the need for the proj4js library. Here's how you can achieve this within Leaflet:

var point = new L.Point(3679364.68,-9096106.74); // Lon/Lat
var earthRadius = 6378137;
var latlng = L.Projection.SphericalMercator.unproject(point.divideBy(earthRadius));

map.panTo(new L.LatLng(latlng.lat, latlng.lng));

Answer №2

I've found a solution by utilizing the proj4js library to transform the coordinates. Here's how I achieved it:

var source = new Proj4js.Proj('EPSG:3857');
var dest = new Proj4js.Proj('EPSG:4326');
var p = new Proj4js.Point(-9096106.74,3679364.68); //this takes x,y
Proj4js.transform(source, dest, p);
this.map.setView(new L.LatLng(p.y, p.x),zoom);

Although this method works, I find it less than ideal due to the library's large file size. I'm still searching for a leaflet solution. Considering that leaflet internally uses EPSG:3857 for tile fetching, there should be a simpler way to accomplish this.

Update

If you prefer a purely Leaflet solution, refer to @ARsl's answer. I'm sticking with my current approach because I find the projection calculations a bit cumbersome, even though they are correct. Additionally, proj4js offers the benefit of supporting more datums.

UPDATE

For an alternative method in Leaflet without proj4js, take a look at @Moos'SamuelSilver's comment on this answer:

Leaflet.CRS.EPSG3857.unproject(Leaflet.point(x,y)) does the job pretty well. Source and further information can be found at leafletjs.com/reference.html#crs

Answer №3

In my search, I have not come across any predefined method for converting EPSG:3857 coordinates to LatLng.

The LeafLet crs class L.CRS.EPSG3857 only offers a project method, which converts L.LatLng to L.Point in EPSG:3857 coordinates. https://github.com/Leaflet/Leaflet/blob/master/src/geo/crs/CRS.EPSG3857.js

However, it is relatively simple to enhance it with an unproject method:

L.CRS.EPSG3857.unproject = function (point) { // Point -> LatLng
  var earthRadius = 6378137;
      projectionPoint = L.point(point).divideBy(earthRadius);

  return this.projection.unproject(projectionPoint);
};

This can then be used with the panTo method:

map.panTo(map.options.crs.unproject([1372720.6476878107, 5690559.995203462]));

or:

map.panTo(L.CRS.EPSG3857.unproject([1372720.6476878107, 5690559.995203462]));

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

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

Error encountered while executing a join query in Node.js

My stack includes express.js, sequelize, and mysql Database Structure A : { id: 1, name: ... } B : { A_id: 1, name: name1 }, { A_id: 1, name: name2 } A Model (models/A.js) A.association = models => { A.hasMany(models.B, { foreignKey: 'A_id&ap ...

Utilize Vue 2.0 to retrieve input from the getmdl-select component

Experimented with getmdl-select using Vue2.0. Managed to get it to display correctly in the view, but the associated model is not updating. Here is the code snippet: <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

How can I achieve a stylish scrolling header similar to a Google Blog for my website?

Google's blog features a unique header design - as you scroll down, the gray bar in the header moves up until it locks at the top of the screen. While CSS's position:fixed can achieve a similar effect, Google seems to have used a combination of p ...

Retrieve information from a JSON file containing multiple JSON objects for viewing purposes

Looking for a solution to access and display specific elements from a JSON object containing multiple JSON objects. The elements needed are: 1) CampaignName 2) Start date 3) End date An attempt has been made with code that resulted in an error displayed ...

Differences in behavior of constructors when utilizing ES6 shorthand notation

ES6 introduced a new way to initialize objects with functions and properties using shorthand notation. // ES6 shorthand notation const obj1 = { a(b) { console.log("ES6: obj1"); } }; // ES5 var obj2 = { a: function a(b) { con ...

Increase the value of $index within the ng-repeat loop

Is there a way to increment the value of $index in ng-repeat by a specific amount? For example, if I want to display two values at a time, how can I ensure that the next iteration starts with the third value instead of the second value? <div ng-contr ...

Adjust input width based on content in VueJS

Is it possible to achieve the following using (Pug & CoffeeScript): input(placeholder="0", v-model.number="order[index]" v-on:change="adjustInput") ... adjustInput: -> event.target.style.width = event.target.value.length + 'ch' Even ...

A step-by-step guide on setting up an event listener for dynamically generated HTML using JavaScript objects

In my JavaScript code, I am creating object instances that include HTML elements in the form of buttons. These buttons are dynamic and have words generated dynamically as well. I want these buttons to execute certain functions when clicked. The challenge I ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Tips for applying and removing classes using an anchor tag

When I click on an anchor, I want it to add a specific class. This is my current markup: <ul> <li> <a href="<?php echo base_url()?>home/promos/call" class="promo-call"></a> </li> ...

Application of id missing on all buttons in Bootstrap tour template

I'm having an issue with applying a new id to the next button in a Bootstrap tour template. I added the id to the button, but it only seems to work for the first stage and not the subsequent ones. Can anyone provide insight into why this might be happ ...

VS code is showing the directory listing instead of serving the HTML file

Recently, I attempted to use nodejs to serve the Disp.html file by following a code snippet from a tutorial I found on YouTube. const http = require("http"); const fs = require("fs"); const fileContent = fs.readFileSync("Disp.html& ...

What is the best way to create a unit test for a function that calls upon two separate functions?

When testing the getAppts function within this module, the correct way to evaluate the code it encompasses may not be entirely clear. Should db.getDatabase() and fetchAppts() be run as stubs inside the unit test function? The current unit test implementati ...

What is causing the most recent iPhones to have issues with my Javascript code?

After analyzing my webserver logs, it appears that an iOS 14 device is categorizing one of my Javascript files as "injected". This file seems to be operating in a separate environment or namespace. As a result, any AJAX attempts made by the script fail bec ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Step-by-step guide to automatically submitting a form after obtaining geolocation without the need for manual button-clicking

I am looking for a way to automatically call a page to get geolocation data, and then submit the form to my PHP page with the values of getlat and getlon without the need to click a submit button. I have tried implementing the code below, however, despit ...

Populate an ng-repeat table again while maintaining its original sorting order

Incorporating a table filled with data fetched from a webservice using the ng-repeat directive, I have enabled sorting functionality for all columns. Additionally, at regular intervals, the application polls the webservice to retrieve updated data. This o ...

No data being fetched through Ajax

I am facing an issue with retrieving PHP data in the form of an array. I have created an AJAX query to display data in two divs: one is a drop-down and the second is where all data will be shown. However, the problem is that when I attempt to do this, all ...