How to get the name of the current city by means of Google Maps?

I have an application in which I would like to display the name of the town or city where the location of the person using the application is located, I currently have the LATITUDE and LONGITUDE. But now I do not know how to proceed.

navigator.geolocation.getCurrentPosition(function(pos) {
    var position = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
}, function (error) {
    // Código de error
});
 5
Author: Chofoteddy, 2015-12-14

4 answers

Uses google.maps.Geocoder

unfortunately this documentation is in English

The way of use is as follows:

var geocoder = new google.maps.Geocoder;
geocoder.geocode({
    'location': '<aquí va la latitud y longitud separadas por una coma>' 
     // ej. "-34.653015, -58.674850"
  }, function(results, status) {
      // si la solicitud fue exitosa
      if (status === google.maps.GeocoderStatus.OK) {
        // si encontró algún resultado.
        if (results[1]) {
          console.log(results[1].formatted_address);
        }
      }
});

Here is a functional example:

initMap();

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: -34.653015,
      lng: -58.674850
    }
  });
  var geocoder = new google.maps.Geocoder;
  var infowindow = new google.maps.InfoWindow;

  document.getElementById('submit').addEventListener('click', function() {
    geocodeLatLng(geocoder, map, infowindow);
  });
}

function geocodeLatLng(geocoder, map, infowindow) {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var latlng = {
    lat: parseFloat(latlngStr[0]),
    lng: parseFloat(latlngStr[1])
  };
  geocoder.geocode({
    'location': latlng
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No hay resultados');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}
#map {
  height: 300px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACJapLIVhm-uVWitwICh24232jYdkP1SQ&signed_in=true"></script>
<input id="latlng" type="text" value="-34.653015, -58.674850">
<input id="submit" type="button" value="Obtenr Nombre">
<div id="map"></div>
 9
Author: rnrneverdies, 2015-12-15 00:23:22

I leave you an example of reverse geolocation

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {lat: 40.731, lng: -73.997}
  });
  var geocoder = new google.maps.Geocoder;
  var infowindow = new google.maps.InfoWindow;

  document.getElementById('submit').addEventListener('click', function() {
    geocodeLatLng(geocoder, map, infowindow);
  });
}

function geocodeLatLng(geocoder, map, infowindow) {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
  geocoder.geocode({'location': latlng}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        map.setZoom(11);
        var marker = new google.maps.Marker({
          position: latlng,
          map: map
        });
        infowindow.setContent(results[1].formatted_address);
        infowindow.open(map, marker);
      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}

Example taken from: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse

 2
Author: GNUrub, 2015-12-15 01:14:19

Here is an example of developing a weather widget where there is a Javascript method where you get the city. http://marcodetrabajo.com/widget-meteorologia-jquery /

var WeatherApi = (function() {
  /* Constantes
   *
   */

  var ENDPOINT = 'http://api.wunderground.com/api/8056d793049f14ea/'; 

  var exports = {};

      /* Función que obtiene, a partir de la latitud y longitud, el nombre de la ciudad y el código del país
       *
       * @param latitude latitud 
       * @idCountry longitude longitud
       */
      exports.getCityAndCountry = function (latitude, longitude){       
        var self = this;
        $.ajax({
          type

: 'GET',
      url: ENDPOINT + 'geolookup/q/'+ latitude +','+ longitude +'.json',
      success: function(coords){            
            self.getWeatherData(coords.location.city, coords.location.country_iso3166);             
      }
    });  
  };


  return exports;
})();

You can use the method as follows: WeatherApi.getCityAndCountry(tuLatitud, tuLongitud)

Greetings

 1
Author: vicenrele, 2016-06-23 19:13:16

Good afternoon... And as it would be for when you have multiple markers or points...

Since I have this... I get from a database a json with latitudes and longitudes... and I want to display in a datatable as well as in the map with the markers... I want something like that...

- - - Latitude: 22 / longitude: 33 / Geocoder address --- latitude: 23 / longitude: 34 / Geocoder direction --- latitude: 24 | longitude: 35 / Geocoder address

        $.ajax({
            url: 'db/utilities.php?accion=listar-puntos-busqueda',
            dataType: 'json',
            success: function(resultado){

                if((resultado.length-1) > 0){

                    mostrarPuntos(resultado);
                }                    
            }
        })

var geocoder;
function mostrarPuntos(array) {

    tablaPuntos.clear().draw();

    geocoder = new google.maps.Geocoder();

    var bounds = new google.maps.LatLngBounds();
    var map = new google.maps.Map(document.getElementById("map"), {
      mapTypeId: 'roadmap'
    });
    map.setTilt(50);

    var coordenadas = new Array();
    for(var i = 1; i < array.length; i++) {

        var coordenada = new Array();
        coordenada.lat = parseFloat(array[i][2]);
        coordenada.lng = parseFloat(array[i][3]);

        var punto = new google.maps.LatLng(coordenada.lat, coordenada.lng);
        bounds.extend(punto);

        geocoder.geocode({'latLng': punto}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var marker = new google.maps.Marker({
                        map: map,
                        position: punto,
                        label: array[i][0]
                    });
                    tablaPuntos.row.add( [
                        array[i][0],
                        array[i][1],
                        results[0].formatted_address
                    ] ).draw();
                }
            }
        }); 

        coordenadas.push(coordenada);
        map.fitBounds(bounds);

    }

    var ruta = new google.maps.Polyline({
        path: coordenadas,
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 5
    });
    ruta.setMap(map);

}

But at the time of run... only one position is displayed on the map and the first data in the table... it's like I'm not going through the geocoder anymore...

Where is the error...??

In advance thank you very much..

 0
Author: Diego Yamberla, 2017-12-29 22:26:46