How do I take the position of a marker on a map and adc in a text field automatically each time I place this marker?

Asked

Viewed 56 times

4

inserir a descrição da imagem aqui

function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent("You clicked the map at " + e.latlng.toString())
            .openOn(macarte);
        var marker= L.marker(e.latlng).addTo(macarte)
        
    }
 <title>Cadastro </title>
 

    <h2>Cadastre as Coordenadas </h2> 

   <table>
  <h3> <label for="Endereco">Endereço:</label> </h3>
  <input id="endereço"/>

  <h3> <label for="latitude">Latitude:</label> </h3>
    <input id="lat"/>
    
   <h3> <label for="longitude">Longitude:</label> </h3>
    <input id="lon"/>
<br> </br>
    <button> Salvar </button>

  • What map are you talking about? Enjoy and adjust your for=""

  • openstreetmap with leaflet library

  • and you can’t add it to the question?

  • I’m going to try

  • I could only get the image right

  • as soon as I click anywhere on the map, it shows in the marker longitude and latitude and it is this information that I want to put in those last two fields automatically

Show 1 more comment

1 answer

1


Note that the value of e.latlng.toString() returns a string in the pattern:

LatLng(n1, n2)

Where n1 and n2 are numbers that can be negative and have decimal places separated by point.

In this case, you can use a regular expression to return only n1 and n2. The expression would be:

/[\d|\.|-]+/g

Will only fetch numbers (\d), dot (\.) or the negative sign (hyphen -). The plus sign + at the end serves to merge 1 or more occurrences. The character | means "or". See that I put what I want to find between brackets [], which represents the whole of what I want to find, separated by |. That is, I want to find numbers or point or hyphen, the rest is discarded. The g is a flag to fetch all occurrences in the string, not just the first one you find.

This regular expression, using .match(), will return an array with the two values:

[n1, n2]

So just take the index 0 (n1) and play in latitude input and index 1 (n2) in the longitude input.

Your function will look like this:

function onMapClick(e) {
   popup
   .setLatLng(e.latlng)
   .setContent("You clicked the map at " + e.latlng.toString())
   .openOn(macarte);
   var marker= L.marker(e.latlng).addTo(macarte)

   var coords = e.latlng.toString().match(/[\d|\.|-]+/g);
   document.getElementById("lat").value = coords[0];
   document.getElementById("lon").value = coords[1];
}

An example of functioning:

var string = "LatLng(-25.9898, -50.8877)";
var coords = string.match(/[\d|\.|-]+/g);
document.getElementById("lat").value = coords[0];
document.getElementById("lon").value = coords[1];
Lat:<input id="lat"/>
<br>
Long: <input id="lon"/>

  • Thank you very much, it worked very well !!!!

  • Then you can mark the answer ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.