如何在地图上显示watchposition lat lon

时间:2016-09-20 10:47:05

标签: javascript cordova google-maps

我正在使用cordova通过watchPosition()方法找出设备位置。我能够成功找回位置但是 我想将watchposition()的纬度和经度值传递给谷歌地图。我怎么能这样做?

的index.html

<div id="map"></div>
<script>
  var map;
  function initMap() {
    var myLatLng = {
        //here the lat and lon should update on intervals
    };

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'Hello World!'
    });
  }
</script>

app.js

$("#getGeolocation").on('click', function(){
        document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady() {          
               function onSuccess(position) {
                    var element = document.getElementById('geolocation');
                    element.innerHTML = 'Latitude: '  + position.coords.latitude      + '<br />' +
                                        'Longitude: ' + position.coords.longitude     + '<br />' +
                                        '<hr />'      + element.innerHTML;
                }

                function onError(error) {
                    alert('code: '    + error.code    + '\n' +
                          'message: ' + error.message + '\n');
                }

                var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 3000 });
        }
    });

2 个答案:

答案 0 :(得分:1)

onSuccess事件处理程序中更新标记的位置,如下所示:

function onSuccess(position) {
   var pos = {
      lat: position.coords.latitude, 
      lng: position.coords.longitude 
   };

   // Center map
   map.setCenter(pos);

   // Update marker position
   marker.setPosition(pos);
}

答案 1 :(得分:0)

这是通过传递经度和纬度来显示谷歌地图的JavaScript。

     var myLatlng = new google.maps.LatLng(-34.397, 150.644);
              var myOptions = {
                zoom: 8,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              }
              var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);