I have a use case for a map that requires showing a marker with the same lat/lng for it’s origin and destination.
However, I find that it often results in these:
where the marker is not centered and if I’m using it on mobile it just cannot be seen.
Is there a way to control the zoom in this scenario?
This is the current code I'm using. I've tried using LatLng Bounds but no luck with that.
<!doctype html>
<html>
<head>
<meta name='viewport' content='initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, shrink-to-fit=no' />
<title>Simple Map</title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.custom-marker {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
background-color: #32a852;
color: #FFFFFF;
border-radius: 50%;
font-size: 16px;
font-family: Arial, sans-serif;
text-align: center;
line-height: 10px;
white-space: nowrap;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
let map;
//remove when replacing with actual values
let lat1 = 1.452728;
let lng1 = 103.816431;
let lat2 = 1.452728;
let lng2 = 103.816431;
async function initMap() {
// Request needed libraries.
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
map = new Map(document.getElementById("map"), {
center: { lat: (lat1 + lat2) / 2, lng: (lng1 + lng2) / 2 },
zoom: 1,
mapTypeId: "roadmap",
streetViewControl: false,
mapTypeControl: false,
rotateControl: false,
mapId: "4504f8b37365c3d0",
});
const originMarker = document.createElement('div');
originMarker.className = 'custom-marker';
//customize originMarker
/*
originMarker.style.background = "blue";
originMarker.style.color = "white";
originMarker.style.fontSize = "";
originMarker.textContent = "You"
*/
// Marker
const origin = new AdvancedMarkerElement({
map,
position: { lat: lat1, lng: lng1 },
content: originMarker
});
const destination = new AdvancedMarkerElement({
map,
position: { lat: lat2, lng: lng2 },
});
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
polylineOptions:{
strokeColor: "#F33F33",
strokeOpacity: 1,
strokeWeight: 5,
}
});
const request = {
origin: new google.maps.LatLng(lat1, lng1),
destination: new google.maps.LatLng(lat2, lng2),
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(request, (response,status) => {
if (status === 'OK') {
directionsRenderer.setDirections(response);
} else {
console.error('Directions request failed due to the following error: ' + status);
}
});
}
initMap();
</script>
<script async
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
</body>
</html>