Find out the city by Google maps coordinates

I have a map on the site with a search, Is it possible to pull out separately only the name of the city in which the coordinates were marked on the map? I tried it like this

  var places = searchBox.getPlaces();
  siti = places[0].address_components[3].long_name;

If you enter something like this address Тверская улица, 4, Москва, Россия, it works, but if the address is something like that Московская область, Мытищинский район, МКАД 84 км, ТПЗ Алтуфьево, владение 3, стр. 1.

places[0].address_components

There is no such property. Here is actually my map with search:

 function init() {
   var map = new google.maps.Map(document.getElementById('map-canvas'), {
     center: {
       lat: 12.9715987,
       lng: 77.59456269999998
     },
     zoom: 12
   });


   var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
   map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('pac-input'));
   google.maps.event.addListener(searchBox, 'places_changed', function() {
     searchBox.set('map', null);


     var places = searchBox.getPlaces();

     var bounds = new google.maps.LatLngBounds();
     var i, place;
     for (i = 0; place = places[i]; i++) {
       (function(place) {
         var marker = new google.maps.Marker({

           position: place.geometry.location
         });
         marker.bindTo('map', searchBox, 'map');
         google.maps.event.addListener(marker, 'map_changed', function() {
           if (!this.getMap()) {
             this.unbindAll();
           }
         });
         bounds.extend(place.geometry.location);


       }(place));

     }
     map.fitBounds(bounds);
     searchBox.set('map', map);
     map.setZoom(Math.min(map.getZoom(),12));

   });
 }
 google.maps.event.addDomListener(window, 'load', init);
html,
body,
#map-canvas {
  margin: 0;
  padding: 0;
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div class="container" id="map-canvas" style="height:300px;"></div>

2 answers

To get the coordinates of a specific address, use geocoder.geocode with a promise.

Geocoder.geocode + promise:

function geocode(address) {
  let geocoder = new google.maps.Geocoder();

  return new Promise(function(resolve, reject) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        resolve(results);
      } else {
        reject(status);
      }
    });
  });
}

geocode("Тверская улица, 4, Москва, Россия")
  .then(resolve => {
    alert("Тверская улица, 4, Москва, Россия: " + resolve[0].geometry.location);
  })
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>

To perform reverse geocoding, i.e. translate coordinates to an address, use the following code.

Reverse geocoding:

new google.maps.Geocoder().geocode({
  'latLng': new google.maps.LatLng(12.9715987, 77.594562699)
}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    console.log(results);
  }
});
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
In this example, you can see what data the object contains after executing the request. You can get everything you need out of it.

An example for your case:

function geocode(address) {
  let geocoder = new google.maps.Geocoder();

  return new Promise(function(resolve, reject) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        resolve(results);
      } else {
        reject(status);
      }
    });
  });
}

geocode("Тверская улица, 4, Москва, Россия")
  .then(resolve => {
    return resolve[0].geometry.location;
  })
  .then(resolve => {
    new google.maps.Geocoder().geocode({
      'latLng': resolve
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          var country = null,
            countryCode = null,
            city = null,
            cityAlt = null;
          var c, lc, component;
          for (var r = 0, rl = results.length; r < rl; r += 1) {
            var result = results[r];

            if (!city && result.types[0] === 'locality') {
              for (c = 0, lc = result.address_components.length; c < lc; c += 1) {
                component = result.address_components[c];

                if (component.types[0] === 'locality') {
                  city = component.long_name;
                  break;
                }
              }
            } else if (!country && result.types[0] === 'country') {
              country = result.address_components[0].long_name;
              countryCode = result.address_components[0].short_name;
            }

            if (city && country) {
              break;
            }
          }

          document.getElementById('city').innerHTML = city;
          document.getElementById('country').innerHTML = country;
          document.getElementById('countryCode').innerHTML = countryCode;
        }
      }
    });
  })
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<ul id="x">
  <li>Город: <span id="city"></span></li>
  <li>Название страны: <span id="country"></span></li>
  <li>Код страны: <span id="countryCode"></span></li>
</ul>

You should clearly understand that there are addresses that are not geographically located in the city (outside the city, etc.) and in this case you can not get the city in which this address is available, but you can get the name of the city that is the administrative center of the region that corresponds to your address Московская область, Мытищинский район, МКАД 84 км, ТПЗ Алтуфьево, владение 3, стр. 1, using result.types[i] === 'political'.

 3
Author: , 2018-09-27 09:40:41

In your question, you ask:

If you enter something like this address "Tverskaya Street, 4, Moscow, Russia", it works, but if the address is something like "Moscow region, Mytishchi district, MKAD 84 km, TPZ "Altufevo", possession 3, p. 1", there is no such property.

I checked this address with the tool Latitude and Longitude of a Point of iTouchMap. As a result, I got the coordinates of Toyota Motors:

Map of the Moscow region, Toyota Motors

Apply this code from the Google documentation Places search box:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Searchbox</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 300px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #target {
        width: 345px;
      }
    </style>
  </head>
  <body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>
    <script>
      // This example adds a search box to a map, using the Google Place Autocomplete
      // feature. People can enter geographical searches. The search box will return a
      // pick list containing a mix of places and predicted search terms.

      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

      function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -33.8688, lng: 151.2195},
          zoom: 13,
          mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

          if (places.length == 0) {
            return;
          }

          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });
          markers = [];

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              return;
            }
            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
              map: map,
              icon: icon,
              title: place.name,
              position: place.geometry.location
            }));

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
      }

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
         async defer></script>
  </body>
</html>

If you enter the phrase in the search field: "Moscow region, Mytishchi district, Toyota Motor", then the map will give you this place. This phrase is a localization for this and a specific Toyota Motors company. Perhaps you should avoid specifying the exact email addresses and include phrases in the content of the web pages that localize specific businesses, and that will meet the expectations of users looking for a business by its name and / or brand, rather than by postal address (few people know this).

 0
Author: nikant25, 2017-10-21 07:02:47