[問題] google map api 函數使用問題

作者: ww410490 (致命伸卡球)   2014-04-29 13:06:02
各位前輩、大大好
小弟欲練習google map api,手邊資料有數筆經緯度資料
想法是:
先利用reverse geocoding,將經緯度轉換成地址地名,
再利用direction service,帶入地址一和地址二當作起點和終點,
最後得到地址一和地址二的路徑規劃路線。
code如下:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Reverse Geocoding</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script
src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var lat = [];
lat[0] = "40.714224";
lat[1] = "41.714224";
lat[2] = "42.714224";
var lng = [];
lng[0] = "-73.961452";
lng[1] = "-74.961452";
lng[2] = "-75.961452";
function initialize() { //先呈現地圖 和得到地址資料
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(40.730885,-73.997383);
//var lat = "40.714224";
//var lng = "-73.961452";
var i = 1;
var latlng = new google.maps.LatLng(lat[i], lng[i]);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
//var name = [];
name = results[1].formatted_address;
//alert(name)
infowindow.open(map, marker);
}
}
});
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function calcRoute() { //開始算路徑
//alert(name);
var start = name;
var end = "st louis, mo";
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
//codeLatLng();
</script>
</head>
<body>
<div id="panel">
<input type="button" value="calcRoute" onclick="calcRoute()">
</div>
<div id="map-canvas"></div>
</body>
</html>
作者: Ammenze (藍天白雲)   2014-04-29 15:41:00
你的directionsDisplay沒有new出來,建議再看一次googlemap範例:http://ppt.cc/Bdje
作者: ww410490 (致命伸卡球)   2014-04-29 16:14:00
多謝1F,目前研究new出來後沒有反應也沒有error的情況..喔喔!再次感謝1F!我懂了!

Links booklink

Contact Us: admin [ a t ] ucptt.com