Alter a map's marker location based on a human-readable address. This code needs to be repurposed, but here it is pulled raw from another project. In this example, the address is derived from the value of a text input. The context: a user went to a page and entered their address and zip. If their zip is not available in the system yet, they are redirected to a "Coming Soon" page. On page load, the embedded map's marker is automagically set to the address they specified.
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 27.7712671,
lng: -82.645638
},
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('addressid');
var input_val = input.value;
var searchBox = new google.maps.places.SearchBox(input);
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Set the map marker address on initial page load
// so that it is correct when the user is redirected
// to the "coming soon" page.
function initMapPageLoad() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': input_val }, function( results, status ) {
if ( status == google.maps.GeocoderStatus.OK ) {
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
console.log("Address set to: " + input_val);
}
else {
console.log("There was a problem with geolocation.");
}
});
}
google.maps.event.addDomListener( window, 'load', initMapPageLoad );