javascriptgoogle-mapsgoogle-maps-api-3

Why does Google Map restrict the zoom if the origin and destination are the same places?


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:

Image

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>
 

Solution

  • The bounds returned by the directions service for that route is not centered on the marker. Use preserveViewport: true (on the directionsRenderer) and set the map center and zoom manually for this case if that is an issue.

            const directionsRenderer = new google.maps.DirectionsRenderer({ 
              preserveViewport: true,
    
    
            directionsService.route(request, (response,status) => {
              if (status === 'OK') {
                directionsRenderer.setDirections(response);
                map.setZoom(22);
              } else {
                console.error('Directions request failed due to the following error: ' + status);
              }
            })
    

    working code snippet:

         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",
            });
            console.log("map original center="+map.getCenter());
    
           const originMarker = document.createElement('div');
           originMarker.className = 'custom-marker';
    
          // 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({ 
              preserveViewport: true,
              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') {
              console.log(response.routes[0].bounds.toUrlValue());
                directionsRenderer.setDirections(response);
                map.setZoom(22);
              } else {
                console.error('Directions request failed due to the following error: ' + status);
              }
            });
          }
          initMap();
          #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;
        }
    <!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>
      </head>
      <body>
        <div id="map"></div>
        <!-- prettier-ignore -->
        <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
            ({key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk", v: "weekly"});</script>
      </body>
    </html>