我正在使用Google Maps JS API创建我自己的风格地图。我想在地图上添加方向功能,我遵循了官方教程(在显示方向结果标题下),但最终路线没有出现。。。
我调试了我的代码,发现directionsService.route函数返回google.maps.DirectionsStatus.OK和directionsDisplay.setDirections(result)真的被调用,没有JS错误。。。因此,方向被成功计算,但没有显示在我的地图上。A试图关闭特殊的地图样式,但即使在默认的地图样式上,它也不会出现。有什么想法吗?问题出在哪里?
好的,一些代码…:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAB2gbXmG... ...mNs66iPr8&sensor=false&callback=directions_init"></script>
<script type="text/javascript">
var map;
var zoom = 11;
var directionsDisplay;
var directionsService;
function gmap_init(){
var styleArray = [ /*here is style but even if its commented its not working*/];
var alterMapStyle = new google.maps.StyledMapType(styleArray, {name: "ALTER style"});
var latlng = new google.maps.LatLng(/*lat, lng*/);
var myOptions = {
zoom: zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
zoomControl: false,
scaleControl: false,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("gmap"), myOptions);
map.mapTypes.set('ALTER_style', alterMapStyle);
map.setMapTypeId('ALTER_style');
}
function directions_init(){
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
display_route();
}
function display_route(){
var request = {
origin: 'Place A',
destination:'Place B',
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//program got here without error
directionsDisplay.setDirections(result);
}
});
}
不确定这是否是问题的根源,但肯定值得一试。。。从您的脚本输入
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAB2gbXmG... ...mNs66iPr8&sensor=false&callback=directions_init"></script>
我假设directions_init函数是在下载api脚本之后调用的,这可能是在页面的onload事件之前,因此您的映射对象尚未启动,并且为null。所以实际上你在打
directionsDisplay.setMap(null);
尝试从gmap_init或在onload后触发的任何事件上调用directions_init。