I want to have an input
which gets user’s
given address and creates a google maps instance based on the given address,
And embed it in website.
Is there a way to implement this?
You can do this with the Maps API (first you need to sign up, create a project, and enable the "Google Maps JavaScript API" for your project).
To load the API, you need to include it in the head
tag of your website.
<!DOCTYPE html>
<html>
<head>
<!-- ... -->
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
</head>
<body>
<!-- ... -->
</body>
</html>
where API_KEY
is your key.
Then, in the body, make the input tag with a button to call a javascript function to open the map
<input type="text" id="inputted-address" placeholder="Type address here">
<button onclick="showMap()">Show Map</button>
<div id="map"></div>
Last, add javascript to define the function showMap()
used above. Something like this:
<script>
function showMap() {
var address = document.getElementById('inputted-address').value;
// convert the address to latitude & longitude
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: address }, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
// Create the map centred on the user-inputted address
var map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 15 // initial zoom level (change if you want)
});
var marker = new google.maps.Marker({
map: map,
position: location,
title: 'Inputted location'
});
} else {
alert('Hmm. Seems there was a problem: ' + status);
}
});
}
</script>