JSFiddle - React, Tailwind, and code Playground
by huppen
HTML
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<a class="route-1" href="#">Bahnhof</a>
<a class="route-2" href="#">MHB</a>
<a class="route-3" href="#">Innenstadt</a>
<div id="map-canvas"></div>
CSS
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
JavaScript
//Custom Google Routing on Map
$(".route-1").click(function() {
initMap();
});
$(".route-2").click(function() {
initMapb();
});
$(".route-3").click(function() {
initMapc();
});
var startA = new google.maps.LatLng(52.400996, 12.552875);
var zielA = new google.maps.LatLng(52.400906, 12.566189);
var startB = new google.maps.LatLng(52.400996, 12.552875);
var zielB = new google.maps.LatLng(52.410747, 12.548135);
var startC = new google.maps.LatLng(52.400996, 12.552875);
var zielC = new google.maps.LatLng(52.408747, 12.563061);
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
avoidTolls: true,
avoidHighways: false,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Es ist ein Fehler aufgetreten: ' + status);
}
});
}
function initMap() {
var pointA = startA,
pointB = zielA,
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "red"
},
map: map
}),
markerA = new google.maps.Marker({
//position: pointA,
//title: "Gödenstraße",
//label: "A",
map: map
}),
markerB = new google.maps.Marker({
//position: pointB,
//title: "Brandenburg HBF",
//label: "B",
map: map
});
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
//Center map on window resize
var center = map.getCenter();
google.maps.event.addDomListener(window, 'resize', function()...