JSFiddle - React, Tailwind, and code Playground
by refan
HTML
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false"></script>
<form id="form1" runat="server">
Lat:
<input type="text" id='lat'> Lon:
<input type="text" id='lon'>
<center>
<!-- MAP HOLDER -->
<div id="gmap"></div>
<!-- REFERENCES -->
lat: lon:
</center>
</form>
CSS
div#gmap {
width: 80%;
height: 500px;
border: double;
}
JavaScript
var map;
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function calcRoute(start, end) {
directionsDisplay.setMap(map);
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
console.log(response);
alert(status);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function initialize() {
var myLatlng = new google.maps.LatLng(35.18061975930, 51.36565089010);
var myOptions = {
zoom: 7,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("gmap"), myOptions);
// marker refers to a global variable
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.addListener(map, "click", function(event) {
// get lat/lon of click
var clickLat = event.latLng.lat();
var clickLon = event.latLng.lng();
// show in input box
document.getElementById("lat").value = clickLat.toFixed(5);
document.getElementById("lon").value = clickLon.toFixed(5);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(clickLat, clickLon),
map: map
});
var newLatLon = new google.maps.LatLng(clickLat, clickLon);
calcRoute(myLatlng, newLatLon);
});
}
window.onload = function() {
initialize()
};