谷歌地图geolocation.geolocate给出地图,但没有方向

时间:2013-05-09 22:04:18

标签: javascript google-maps-api-3 geolocation

所以我制作了这段代码,将普通地址转换为地理位置,并从你的gps位置(phonegap位置,html5位置或任何latlng)返回一张地图和路线。在phonegap或html5位置成功时调用此函数。

此代码在浏览器中正常运行,但在以下情况下失败: 错误:TypeError:'undefined'不是file:// bla bla第761行的对象

第761行= geocoder.geocode({'地址':地址},功能(结果,状态){

所以我检查了所有变量,并且它们不是空的,就像在线版本和返回div一样。所以我猜测geolocator链接到谷歌有什么问题。

有趣的是,它显示地图但不显示方向。它标志着你需要去的地方,但不是你所在的位置。它似乎只是方向不加载或什么。

var directionDisplay;
var directionsService = new google.maps.DirectionsService();

function bring_me_back(call_back_map,call_back_directions,address,position) {
var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); // your location
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true
};

var map = new google.maps.Map(document.getElementById(call_back_map),myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById(call_back_directions));
var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title:"My location"
});
// find the address
var geocoder = new google.maps.Geocoder (map);
geocoder.geocode ( { 'address': address }, function(results, status)  {
    if (status == google.maps.GeocoderStatus.OK)  {
        var end = results [0].geometry.location;
        map.setCenter(results [0].geometry.location);
        marker.setPosition(results [0].geometry.location);
        var start = latlng; // your gps location 
        var request = {
            origin:start,
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.WALKING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            } else  alert("Directions was not successful for the following reason: " + status);
        });
    }
    else {
        $('#'+call_back).html("Geocode was not successful for the following reason: " + status);
    }
});
}

我称之为谷歌的方式(它有足够的时间加载和“初始化”在我使用此代码之前被称为方式)。

function loadGoogleScript() {
if(!(navigator.network.connection.type == Connection.NONE)) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://maps.google.com/maps/api/js?v=3.6&sensor=false&callback=initialize';
    document.body.appendChild(script);
    return true;
}
else {
    return false;
}

}

来自API的反馈是有限的,所以我无法做更多的事情。

1 个答案:

答案 0 :(得分:0)

经过一番搜索后,我发现了一个变量:

var directionsService = new google.maps.DirectionsService();

在加载谷歌脚本之前调用。将其更改为

var directionsService;

并致电:

directionsService = new google.maps.DirectionsService();

从功能内部。

感谢您的帮助。