Sometimes, we want to use address instead of longitude and latitude with Google Maps API and JavaScript.
In this article, we’ll look at how to use address instead of longitude and latitude with Google Maps API and JavaScript.
How to use address instead of longitude and latitude with Google Maps API and JavaScript?
To use address instead of longitude and latitude with Google Maps API and JavaScript, we can use geocoding.
For instance, we write
const addressesArray = [
"Address Str.No, Postal Area/city",
//...
];
const map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 12.7826,
lng: 105.0282,
},
zoom: 6,
gestureHandling: "cooperative",
});
const geocoder = new google.maps.Geocoder();
for (const address of addressArray) {
geocoder.geocode(
{
address,
},
(results, status) => {
if (status === "OK") {
const marker = new google.maps.Marker({
map,
position: results[0].geometry.location,
center: {
lat: 12.7826,
lng: 105.0282,
},
});
} else {
cinsole.log(
"Geocode was not successful for the following reason: ",
status
);
}
}
);
}
to create a map with the google.maps.Map
constructor.
Then we create a Geocoder
object.
Next we loop through the addressArray
with a for-of loop.
In it, we call geocoder.geocode
with an object with the address
property to to get the location with results[0].geometry.location
.
Conclusion
To use address instead of longitude and latitude with Google Maps API and JavaScript, we can use geocoding.