How do I pull strings from the URL and mount a specific array for the Google Maps API?

Asked

Viewed 52 times

1

I’m trying to assemble a map of google maps with some pins, where the strings will be passed through the URL.

However I need to pass an array like this to the API:

var locations = [
  ['First Place', -37.808204, 144.855579],
  ['Second Place', -37.675648, 145.026125],
  ['Third Place', -37.816935, 144.966877]
];

In my code I managed to get the parameters and mount an array, but it’s not like what I need and I’m not sure how to improve. This is the code I’ve assembled so far:

var query = location.search.slice(1);
var places = query.split('&');
var locations = [];
places.forEach(function (place) {
    var chaveValor = place.split('=');
    var local = chaveValor[0];
    var cordenadas = chaveValor[1].split(",");
    locations[local] = cordenadas;
});

console.log(locations);

assuming the url is:

https://localhost/GoogleMaps/index.html?First-Place=-37.808204,144.855579&Second-Place-Teste=-37.675648,145.026125

It’s returning the following:

[First-Place: ["-37.808204", "144.855579"], Second-Place-Teste: ["-37.675648", "145.026125"]]

Thank you very much for those who can help.

1 answer

1


Use the second argument from forEach which returns the index of the array to mount the new array:

places.forEach(function (place, i) {
                                ↑
                             índice

And put the argument (in the case, represented by the variable i) in place of local in:

locations[i] = cordenadas;

And add one more line using .unshift to add the variable local as the first value of each array:

locations[i].unshift(local);

Will stay like this:

var query = location.search.slice(1);

var places = query.split('&');
var locations = [];
places.forEach(function (place, i) {
    var chaveValor = place.split('=');
    var local = chaveValor[0];
    var cordenadas = chaveValor[1].split(",");
    locations[i] = cordenadas;
    locations[i].unshift(local);
});

console.log(locations);

The return of this will be:

inserir a descrição da imagem aqui

If you want coordinate values to be stored in numerio value (not string), you can convert using parseFloat() within a .map(). Just change the line:

locations[i] = cordenadas;

For:

locations[i] = cordenadas.map( function(v){ return parseFloat(v); });

The result now will be:

inserir a descrição da imagem aqui

  • Thank you very much friend, solved my problem.

  • 1

    Blz... I added some more information at the end of the reply. Abs!

Browser other questions tagged

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