JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<body onload="initialize()">
<div id="map-canvas"></div>
<div id="locationInput">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
CSS
#map-canvas {
width:70%;
height:480px;
margin:0 auto;
}
#locationInput {
width:50%;
text-align:center;
margin:0 auto;
}
JavaScript
var geocoder;
var map;
var address;
var infowindow;
var marker;
var currentAddress;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
addMarker('campbelltown, NSW');
addMarker('sydney, NSW', 'siteLocation');
addMarker('oak flats, NSW');
}
function getCurrentAddress(marker) {
currentAddress = "Address: ";
geocoder.geocode({
'latLng': marker.getPosition()
}, function (results, status) {
console.log(results[1]);
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) currentAddress += results[1].formatted_address;
console.log(currentAddress);
} else {
currentAddress = "Geocoder failed due to: " + status;
}
return currentAddress;
});
//return 'Address is: ' + marker.getPosition().lat().toFixed(6) + ' , ' + marker.getPosition().lng().toFixed(6);
}
function addMarker(address, markerType) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (markerType == 'siteLocation') {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png",
draggable: true,
clickable: true
});
} else {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: true,
...