Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API - position/center by keyword (city name)

In my web application I am using the gmap javascript API (https://developers.google.com/maps/documentation/javascript/ ). I am using the code below inside a function to position/center the gmap once a user has pressed a button.

var position = new google.maps.LatLng(lat, lng);
map.setCenter(position);

This code uses the latitude and longitude. Instead of the latitude and longitude I would like to position/center the gmap based on a given keyword. For example, how can I position/center the gmap if the input is 'Paris'?

like image 523
user3398797 Avatar asked Jul 17 '17 00:07

user3398797


1 Answers

You can use geocoder service of Maps JavaScript API to resolve your input (e.g. Paris) to coordinate and center the map.

Have a look at the following code sample

var map;
function initMap() {
  var geocoder = new google.maps.Geocoder();

  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 0, lng: 0},
    zoom: 8
  });

  geocoder.geocode({'address': "Paris"}, function(results, status) {
    if (status === 'OK') {
      map.setCenter(results[0].geometry.location);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });


}
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" async defer></script>
like image 175
xomena Avatar answered Sep 18 '22 17:09

xomena