0

I am trying to make a program that creates a google map based off the address given by user input. As i can not manually embed a link for each page, how can i make it so that when a user answers a form with the address I can take that address and make a google map. Do i have to convert the address to latitude and longitude and then do that?

1 Answers1

1

Regarding the Google maps javascript API, you need the latitude (lat) and longitude (lng) to place a marker on map. To find the lat and lng of an adress, you need a geocoding service.

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map.

It exist a lot of geocoding services and Google Cloud Plateform provide one. First, you need to activate the Geocoding API in your acount (see this page from the documentation).

By using geocoding API

To find an adress (exemple: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"), it's just a simple get request to the API with something like

https://maps.googleapis.com/maps/api/geocode/jsonaddress=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

You can get the lat/lng from the JSON response and use it to place your marker on the map. To do it, just follow the instruction from the documentation and you be able to place your marker by doing something like

let myLatLng = {lat:myLatitude, lng:myLongitude};
new google.maps.Marker({
    position: myLatLng,
    map
});

By using Geocoder()

Like @JeremyW says, you can also call the geocoding service by using the Geocoder class from Google map javascript API (see this post).

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

then...

let adress = "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA";
geocoder.geocode( { 'address': address}, function(results, status){
    if(status == google.maps.GeocoderStatus.OK){
        if(status != google.maps.GeocoderStatus.ZERO_RESULTS){      
            let marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map
            });
         }
         else{
             console.log("No results found");
         }
    }
    else{
        console.log("Geocode was not successful for the following reason: " + status);
    }
}
PaulCrp
  • 624
  • 1
  • 8
  • 19