簡體   English   中英

如何在Android手機上使用本地Google Maps .html文件平移到當前位置?

[英]How to pan to current location with local Google Maps .html file on android phone?

目標是在 Android 手機上擁有一個本地 .html 文件,可以使用標准網絡瀏覽器打開該文件,該瀏覽器具有平移到 Google 地圖上當前位置的功能。 目前,平移到當前位置適用於 Android 手機上的 mi 瀏覽器,但最終用戶希望它適用於標准網絡瀏覽器(例如 Chrome)。

預期結果:頂部的“平移到當前位置”按鈕將 Google 地圖平移到手機的當前位置。 實際結果:在 chrome、firefox、edge web 瀏覽器上可以打開 html 文件,但按鈕不會平移到手機上的當前位置。 在筆記本電腦上的 chrome 瀏覽器中,按鈕會平移到當前位置。 在 Android 手機上的 mi 瀏覽器(來自小米)上,按鈕確實響應並平移到當前位置。

由於我是 HTML/JS 的初學者,我不知道這個錯誤是否可以在代碼中修復,或者可以通過網絡瀏覽器中的設置修復。 獲得一種在具有“平移到當前位置”功能的 android 手機上查看本地 html 的方法,並了解它為什么不起作用會很好。

如果要運行代碼,應檢索 Google Maps API 密鑰。 這是示例代碼:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key={GOOGLE_MAPS_API_KEY}&sensor=true">
    </script>
    <script type="text/javascript">

function initialize() {

var mapOptions = {
    zoom: 15,
    center: new google.maps.LatLng(51.924003,4.4601963),
    mapTypeId: google.maps.MapTypeId.HYBRID }
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
const locationButton = document.createElement("button");
  locationButton.textContent = "Pan to Current Location";
  locationButton.classList.add("custom-map-control-button");
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
  locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          infoWindow.setPosition(pos);
          infoWindow.setContent("Location found.");
          infoWindow.open(map);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, infoWindow, map.getCenter());
        }
      );
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
  <div id="map-canvas"/>
  </body>
</html>

當前的解決方案是通過 Azure 將 .html 發布為網站。 該網站可以通過瀏覽器在手機上訪問,並且具有“平移到當前位置”的功能。

javascript 代碼無法通過手機上的本地 .html 文件運行的最可能原因是手機瀏覽器在處理本地 html/javascript 時的安全性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM