0

我一直在关注 HTML5 地理定位教程,并希望修改代码以输入目的地地址的文本,而不是固定目的地。在这段代码中实现它的任何方法都很好。

//这里是java脚本代码

(function(geolocation){

  if (geolocation) return;

  var cache;

  geolocation = window.navigator.geolocation = {};
  geolocation.watchPosition = function(callback){

    if (cache) callback(cache);

    $.getScript('//www.google.com/jsapi',function(){

      cache = {
        coords : {
          "latitude": google.loader.ClientLocation.latitude, 
          "longitude": google.loader.ClientLocation.longitude
        }
      };

      callback(cache);
    });

  };


})(navigator.geolocation);

// Proceed as usual.
(function() {
    if ( navigator.geolocation ) {
    var coords = navigator.geolocation.watchPosition( hereWeGooo,
        function() {
            // failure
                document.body.innerHTML = 'Sorry. We can\'t get your current location.';
            },
            { enableHighAccuracy: true }
        );

    }
function hereWeGooo(coords) {
    coords = coords.coords;
    var latlng = new google.maps.LatLng(coords.latitude, coords.longitude),
        myOptions = {
        //zoom: 15,
        //center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    },
    map = new google.maps.Map(document.querySelector( "#map"), myOptions),
      directionsDisplay = new google.maps.DirectionsRenderer(),
      directionsService = new google.maps.DirectionsService(),

        var dest = document.getElementById('d').value;

    request = {

        origin: latlng,
        destination: dest, 
        // replace with your own airport
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsDisplay.setMap(map);
    directionsService.route(request, function(response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        }
        });
    }
})();

  <form>
    <p><input type="text" id="d" /></p>
    <input type="button" value="Go" onClick="hereWeGooo()">
    </form>
4

1 回答 1

0

你可以这样做:

var dest = document.getElementById('myInput').value;

request = {
    origin: latlng,
    destination: dest, 
//...
}

...然后在您的文档正文中:

<input id='myInput'>

看到链接后补充:

hereWeGooo() 未定义,因为您在应该有分号的地方使用逗号 --- direction.js 第 57 行崩溃。

第 54 到 57 行应该是:

map = new google.maps.Map(document.querySelector( "#map"), myOptions); //<----- semi-colon, not comma
        directionsDisplay = new google.maps.DirectionsRenderer(); //<----- semi-colon, not comma
        directionsService = new google.maps.DirectionsService(); //<----- semi-colon, not comma
于 2012-06-30T14:56:08.753 回答