M
M
mrwitchdoctor2017-08-30 15:06:39
JavaScript
mrwitchdoctor, 2017-08-30 15:06:39

Need to find out the address that a user clicked on in Google Map?

Such task:
When the user clicks on the card, it is necessary to return the received address.
I was able to get the coordinates, but I can’t figure out how to translate them into an address.
I read the Google API documentation, but due to the fact that I'm dumb, I understood little and didn't get to me how to make requests correctly (

function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 44.5452, lng: -78.5389},
          zoom: 9
        });

        map.addListener("click", function( latlng ) {
          var request = {
            location: latlng.latLng,
            query: 'A'
          };

          var service = new google.maps.places.PlacesService(map);
          service.textSearch(request, callback);

          document.getElementById('pops').setAttribute('src', 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + request.location.lat() + ',' + request.location.lng() + '&key=AIzaSyD5oJ7t1DjXJhtWlTuQlzSA63oIHrY5Lh4');

        });

        function callback(results) {
          var marker = new google.maps.Marker({
            map: map,
            place: {
              placeId: results[0].place_id,
              location: results[0].geometry.location,
            }
          });
        }
      }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mrwitchdoctor, 2017-08-30
@mrwitchdoctor

Helped with a decision. If anyone needs:

function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 44.5452, lng: -78.5389},
          zoom: 9
        });

        map.addListener("click", function( latlng ) {

          var link = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng.latLng.lat()
              + ',' + latlng.latLng.lng() + '&key=AIzaSyD5oJ7t1DjXJhtWlTuQlzSA63oIHrY5Lh4';

          $.ajax({
            method: 'post',
            url: link,
            success: function(responce){
              console.log(responce.results[0]);
              /*
               * responce- это объект, нам нужно вернуть свойство, в котором 
               * содержится массив. Из массива выбираем 
               * первый элемент
               */
            },
          });
        });
      }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question