JSFiddle - React, Tailwind, and code Playground
by gchoken
HTML
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&.js"></script>
<div id="map_canvas"></div>
CSS
body, html, #map_canvas {
height:100%;
margin:0;
}
#map_canvas .centerMarker {
position:absolute;
/*url of the marker*/
background:url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat;
/*center the marker*/
top:50%;
left:50%;
z-index:1;
/*fix offset when needed*/
margin-left:-10px;
margin-top:-34px;
/*size of the image*/
height:34px;
width:20px;
cursor:pointer;
}
JavaScript
var map;
var geocoder = new google.maps.Geocoder();
var InfoWindow;
var marker;
function initialize() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(12.9539974,77.6309395),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
codeLatLng();
google.maps.event.addListener(map, 'dragend', function () {
codeLatLng();
});
$('<div/>').addClass('centerMarker').appendTo(map.getDiv())
//do something onclick
.click(function () {
codeLatLng();
});
}
function codeLatLng() {
var c = map.getCenter();
var latlng = new google.maps.LatLng(c.lat(), c.lng());
geocoder.geocode({
'location': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var that = $('.centerMarker');
InfoWindow = new google.maps.InfoWindow({
content: results[0].formatted_address
});
if (that.data('win')) {
that.data('win').close(map);
}
that.data('win', InfoWindow);
that.data('win').bindTo('position', map, 'center');
that.data('win').open(map);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);