Get longitude and latitude from an Address with Google Maps programmatically

After some Googling on how to get Longitude and Latitde from an address using the Maps JavaScript API I soon understood that you actually can’t use this particular API, it is only for displaying the map, but you can easily use another api to do this which works in the same way.

The API we need to use to achieve this is Geocoding API. There you can easily get the longitude and latitude from an address of your choosing. You can complete the previous post if you want to keep up with setting up a project which uses Google Maps to display the visual map, but you can understand how to get the longitude and latitude from an address just by reading this post too!

Okay first, enable the API for Geocoding.

Then have your API key ready which you can get from clicking manage when you found that API and then click on Credentials. Under API Keys is your API key.

. We can get the details of the Google map location by passing in an address into the URL in this manner:

https://maps.googleapis.com/maps/api/geocode/json?address=Zimbabwe&key=MYAPIKEY

Obviously you must replace MYAPIKEY with your actual API key and then address works just like you would search on an address in Google Maps. Let’s add this to our application!

I have a LocationService where I am going to add Observable property called locations:

  locations: Observable<Object>

Then I am going get HttpClient to the constructor:

constructor(httpClient: HttpClient)  

Then add the code for retrieving the Google Maps location data inside the constructor:

  constructor(httpClient: HttpClient) { 
    this.locations = httpClient.get('https://maps.googleapis.com/maps/api/geocode/json?address=Zimbabwe&key=MYAPIKEY') .pipe(
      map((data) => {
        return data;
      }),
      catchError(val => {
        return of(val)
      }),
    );
  }

Then inside a component we call on the method to try it out:

 locationService.locations.subscribe(l => {
      console.log(l);
    });

When we run the application we can see the console.log of the data we get back which is indeed the Google location we wanted (Zimbabwe). That’s basically it!

Now as said previously, I have continued on my previous angular app with google maps project, so we already have the code for showing map markers, and a method to add locations where we want the markers. So what I’ll do is that I go through each location result and add a pin to our Google Map, like this:

    locationService.locations.subscribe((l: any) => {
      l.results.forEach(element => {
        this.addMarker(element.geometry.location)
      });
    });

Now when we look at the map we will see Zimbabwe since that is the address I put into the search url:

https://maps.googleapis.com/maps/api/geocode/json?address=Zimbabwe&key=MYAPIKEY

It’s that easy!

Leave a comment

Your email address will not be published. Required fields are marked *