Javascript:将GPS坐标放入var

时间:2016-05-28 09:00:16

标签: javascript google-maps gps

我很抱歉,但我不是JavaScript方面的专家,我需要在变量中获取纬度和经度来使用Google地图跟踪路线。

    function calcRoute() {
    var start = "position.coords.latitude,position.coords.longitude";
    var end = "<?php echo $la; ?>,<?php echo $lo; ?>";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

如果我写

,此代码有效
        var start = "12.3456789,12.3456789";

正如你所看到的,使用PHP来设置end的coords可以正常工作。我尝试了不同的方法将position.coords.latitude用于结束 var但我不明白为什么“position.coords.latitude,position.coords.longitude”在“12.3456789,12.3456789”中没有变化”

注意:我确信position.coords.latitude和position.coords.longitude填充正确,因为使用警报我可以看到权限值。

感谢您的帮助...

1 个答案:

答案 0 :(得分:0)

你的问题是在javascript中将变量连接到string。如果position.coords.latitudeposition.coords.longitude是一个数字(或者它可能是字符串,在这种情况下并不重要)从中获取"12.3456789,12.3456789"之类的字符串,则必须连接变量使用+运算符。

所以你应该:

var start = position.coords.latitude + "," + position.coords.longitude;

在您的代码中。

修改

一个工作示例:

&#13;
&#13;
function geocode(){
  if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(calcRoute,function(error){
        	alert("Geolocation does not work because:" + error.message);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function calcRoute(position) {
    console.log(position);
    var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
                              
    var geocoder = new google.maps.Geocoder();
    var start = position.coords.latitude + "," + position.coords.longitude;
    var end = "49.200147, 16.607560";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    var directionsService = new google.maps.DirectionsService();
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
        directionsDisplay.setDirections(response);
      }else{
        alert("Direction were not found:" + status);
      }
    });
}
&#13;
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry&dummy=.js"></script>
<body onload="geocode()">
  <div id="map" style="height:400px; width:500px;"></div>
</body>
&#13;
&#13;
&#13;