如果出发地和目的地是同一个地方,为什么谷歌地图会限制缩放?

问题描述 投票:0回答:1

我有一个地图用例,需要显示具有相同纬度/经度的标记作为其出发地和目的地。

但是,我发现它经常会导致以下结果:

图片

标记未居中,如果我在移动设备上使用它,则无法看到它。

这种情况下有没有办法控制变焦?

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>
 
javascript google-maps google-maps-api-3
1个回答
0
投票

该路线的路线服务返回的边界不以标记为中心。如果存在问题,请使用preserveViewport: true(在directionsRenderer上)并针对这种情况手动设置地图中心和缩放。

        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);
          }
        })

工作代码片段:

     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>

© www.soinside.com 2019 - 2024. All rights reserved.