19

Using Google Maps' API v3, how can I geocode a city name, and have a map returned with the outline of the result? usually this is a political entity with strict boundaries, like a city, municipality, etc.

Which API method should be used?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • 1
    There isn't any API (at present) that provides that data. – geocodezip Jul 26 '15 at 16:25
  • 10
    Hello downvoters and closers! **External APIs are strictly on-topic**. If you have an issue with the structure of the question, let us know in the comments! If an API doesn't currently exist for a feature, that's still a valid answer. When that changes at Google, then this question can be updated with a new answer explaining how to use that new API. – p.campbell Jul 26 '15 at 16:29
  • 1
    I´m also looking forward for an API – Daniel Oct 15 '15 at 22:34
  • Did you find a solution yet? – Azad Zain Dec 31 '17 at 11:39
  • @p.campbell find any solution ? I'm also looking for this – kashyap Sep 24 '19 at 05:11

3 Answers3

6

There isn't any API (at present) that provides that data.

Enhancement request

geocodezip
  • 158,664
  • 13
  • 220
  • 245
2

I think you will need Tiger/Line files as referenced in this answer. You can use the data to generate polygons. Use Geocoder.geocode to search for city names. Here's a promise based function that I use:

  function locateAddress(address) {
    var deferred = $q.defer();
    if(!address) { $q.resolve(null); return; }

    var geocoder = new google.maps.Geocoder();

    var a = address;
    if(_.isObject(a)) {
      a = (a.line1 || '') + ' ' + (a.city || '') + ' ' + (a.state || '') + ' ' +  (a.zip || '');
    }

    geocoder.geocode({ 'address' : a}, function(results, status) {
      if(status === 'ZERO_RESULTS') {
        deferred.resolve(null);
        return;
      }

      var c = results[0].geometry.location;
      deferred.resolve({latitude: c.lat(), longitude: c.lng()});
    }, function(err) {
      deferred.reject(err);
    });

    return deferred.promise;
  }
Community
  • 1
  • 1
Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83
1

There is a way to look up the boudary with a combination of different methods.

I have a simple implementation in React, using the geocoder. Basically, I strip the information to get the country name, then use reverse geocoding to get the place id for the country.

 const handleCountrySearch = (country: string) => {
    let geocoder = new google.maps.Geocoder();

    geocoder
      .geocode({
        address: country,
      })
      .then((result: google.maps.GeocoderResponse) => {
        setCountryResult(result.results[0]);
      });
  };

However, you can get a better implementation according to your needs in the Use Places APIs and Geocoding with data-driven styling for boundaries documentation

After that, you can draw using Data Driven styling. Follow this guide from the documentation for Data Driven Styling