JUST HTML/JS和谷歌地图上的实时GPS追踪器可以在手机上运行吗?可能吗?

che*_*unz 30 html javascript gps google-maps tracking

我已经阅读了GPS实时跟踪,并发现了一些关于它的事情,主要需要PHP,zope和数据库来存储传入的数据.其他一些方法使用ajax与PHP的关系.

关于我的问题,是否有可能只使用html和JS,使用标记或其他任何东西来移动Google地图,当你移动到城市的任何地方?需要一些帮助,谢谢!

Dan*_*llo 45

对的,这是可能的.最新智能手机中的大多数浏览器都实现了W3C Geolocation API:

Geolocation API定义了与仅与托管实现的设备相关联的位置信息的高级接口,例如纬度和经度.API本身与底层位置信息源无关.常见的位置信息源包括全球定位系统(GPS)和从网络信号推断的位置,例如IP地址,RFID,WiFi和蓝牙MAC地址,以及GSM/CDMA小区ID,以及用户输入.不保证API返回设备的实际位置.

API旨在实现"一次性"位置请求和重复位置更新,以及显式查询缓存位置的能力.

使用Geolocation API在Google Maps上绘制一个点,看起来像这样:

if (navigator.geolocation) { 
  navigator.geolocation.getCurrentPosition(function(position) {  

    var point = new google.maps.LatLng(position.coords.latitude, 
                                       position.coords.longitude);

    // Initialize the Google Maps API v3
    var map = new google.maps.Map(document.getElementById('map'), {
       zoom: 15,
      center: point,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    // Place a marker
    new google.maps.Marker({
      position: point,
      map: map
    });
  }); 
} 
else {
  alert('W3C Geolocation API is not available');
} 
Run Code Online (Sandbox Code Playgroud)

以上只会收集一次位置,并且在您开始移动时不会自动更新.要处理这个问题,您需要保留对标记的引用,定期调用getCurrentPosition()方法,并将标记移动到新坐标.代码可能如下所示:

// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var marker = null;

function autoUpdate() {
  navigator.geolocation.getCurrentPosition(function(position) {  
    var newPoint = new google.maps.LatLng(position.coords.latitude, 
                                          position.coords.longitude);

    if (marker) {
      // Marker already created - Move it
      marker.setPosition(newPoint);
    }
    else {
      // Marker does not exist - Create it
      marker = new google.maps.Marker({
        position: newPoint,
        map: map
      });
    }

    // Center the map on the new position
    map.setCenter(newPoint);
  }); 

  // Call the autoUpdate() function every 5 seconds
  setTimeout(autoUpdate, 5000);
}

autoUpdate();
Run Code Online (Sandbox Code Playgroud)

现在,如果通过跟踪表示您还应该将此信息存储在服务器上(以便其他人可以看到您从远程位置移动),那么您必须使用AJAX将这些点发送到服务器端脚本.

此外,在您参与此类项目之前,请确保Google Maps API使用条款允许此用法.


更新: W3C Geolocation API公开了一种watchPosition()方法,可以用来代替setTimeout()我们在上面的例子中使用的机制.