javascript for loop将同一组城市打印5次,而不是5组不同的城市
我有一些javascript和html(如下)我正在尝试通过一个城市数组循环,并使用google maps API获取每个城市之间的距离我在两个城市中输入时实现了这一点,但当我在22个城市的数组中硬编码时,每次都会显示相同的城市集,而不是两个城市之间的距离 我猜这与时间有关,谷歌api的返回覆盖了我的变量,但我不知道如何修复它 目前,回路限制为3个,以节省故障排除时的时间 预期产出: 罗斯托克,德国,卢贝克,德国200公里 汉堡罗斯托克100公里 汉堡吕贝克50公里 汉堡,罗斯托克210公里 我得到的是: 汉堡,罗斯托克210公里 汉堡,罗斯托克0公里 汉堡,罗斯托克210公里 汉堡,罗斯托克0公里 汉堡,罗斯托克210公里 我做错了什么javascript for loop将同一组城市打印5次,而不是5组不同的城市,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我有一些javascript和html(如下)我正在尝试通过一个城市数组循环,并使用google maps API获取每个城市之间的距离我在两个城市中输入时实现了这一点,但当我在22个城市的数组中硬编码时,每次都会显示相同的城市集,而不是两个城市之间的距离 我猜这与时间有关,谷歌api的返回覆盖了我的变量,但我不知道如何修复它 目前,回路限制为3个,以节省故障排除时的时间 预期产出: 罗斯托克,德国,卢贝克,德国200公里 汉堡罗斯托克100公里 汉堡吕贝克50公里 汉堡,罗斯托克210公里 我
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<meta name="robots" content="noindex,follow" />
<title>Calculate driving distance with Google Maps API</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
<script type="text/javascript">
// var geocoder, location1, location2, gDir;
//city array
var cities = ["Rostock,Germany",
"Lubeck,Germany",
"Hamburg,Germany",
"Bremen,Germany",
"Hannover,Germany",
"Kassel,Germany",
"Dusseldorf,Germany",
"Koln,Germany",
"St. Augustine,Germany",
"Bonn,Germany",
"Wiesbaden,Germany",
"Frankfurt,Germany",
"Mannheim,Germany",
"Karlsruhe,Germany",
"Baden Baden,Germany",
"Stuttgart,Germany",
"Munich,Germany",
"Nurnberg,Germany",
"Dresden,Germany",
"Leipzig,Germany",
"Berlin,Germany",
"Basel,switzerland"];
function initialize() {
geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
document.getElementById('results').innerHTML = document.getElementById('results').innerHTML+ location1.address+"; "+location2.address+" "+ drivingDistanceKilometers + ' km</br>';
});
}
function getDistance(i,j){
geocoder.getLocations(cities[i], function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(cities[j], function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address"+j);
}
else
{
//alert("i "+i+" "+cities[i]+"; j "+j+" "+cities[j]);
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
function showLocation() {
for(var i=0; i<3; i++){ //adjust loop to match array !!!!!!!!!!!!
for(var j=0; j<3; j++){
var geocoder, location1, location2, gDir;
if(cities[i]==cities[j]){}
else{
initialize()
getDistance(i,j);
}
}
}
}
//<body onload="initialize()">
</script>
</head>
<body >
<form action="#" onsubmit="showLocation(); return false;">
<p>
<input type="text" name="address1" value="Address 1" />
<input type="text" name="address2" value="Address 2" />
<input type="submit" value="Search" />
</p>
</form>
<p id="results"></p>
</body>
</html>
使用谷歌地图API计算驾驶距离
//var地理编码器,位置1,位置2,gDir;
//城市阵列
var cities=[“罗斯托克,德国”,
“德国吕贝克”,
“德国汉堡”,
“不来梅,德国”,
“德国汉诺威”,
“德国卡塞尔”,
“杜塞尔多夫,德国”,
“科隆,德国”,
“德国圣奥古斯丁”,
“德国波恩”,
“威斯巴登,德国”,
“德国法兰克福”,
“德国曼海姆”,
“德国卡尔斯鲁厄”,
“德国巴登巴登”,
“德国斯图加特”,
“德国慕尼黑”,
“德国纽伦堡”,
“德国德累斯顿”,
“德国莱比锡”,
“德国柏林”,
“瑞士巴塞尔”];
函数初始化(){
geocoder=新的GClientGeocoder();
gDir=新的GDirections();
addListener(gDir,“加载”,函数(){
var drivingDistanceMiles=gDir.getDistance().meters/1609.344;
var drivingDistanceKM=gDir.getDistance().meters/1000;
document.getElementById('results')。innerHTML=document.getElementById('results')。innerHTML+location1.address+“;“+location2.address+”“+drivingDistanceKM+”km”;
});
}
函数getDistance(i,j){
geocoder.getLocations(城市[i],函数(响应){
如果(!response | | response.Status.code!=200)
{
警报(“抱歉,我们无法对第一个地址进行地理编码”);
}
其他的
{
location1={lat:response.Placemark[0]。点。坐标[1],lon:response.Placemark[0]。点。坐标[0],地址:response.Placemark[0]。地址};
地理编码器.getLocations(城市[j],函数(响应){
如果(!response | | response.Status.code!=200)
{
警报(“对不起,我们无法对第二个地址进行地理编码”+j);
}
其他的
{
//警报(“i”+i+“”+城市[i]+“j”+j+“”+城市[j]);
location2={lat:response.Placemark[0]。点。坐标[1],lon:response.Placemark[0]。点。坐标[0],地址:response.Placemark[0]。地址};
gDir.load('from:'+location1.address+'到:'+location2.address');
}
});
}
});
}
函数showLocation(){
对于(var i=0;i我看到的一个问题是,在getDistance()
函数中,您正在使用全局变量。我将它们声明为局部变量:
var location1 = {lat: ...
var location2 = {lat: ...
你把一些只需要做一次的事情放到for循环中。
initialize()显然应该只调用一次
我的代码(类似于)您正在尝试执行的操作。请注意:for(var j=i;…j=i所做的是,您不需要两次计算距离(例如:Rostock-Lubeck和Lubeck-Rostock)
一个大问题:谷歌不喜欢你在短时间内发送很多DirectionService请求。
在我测试的地方,谷歌在10次请求后停止。
也许请求之间的延迟可以解决这个问题(我必须检查)
//城市阵列
var cities=[“德国罗斯托克”、“德国卢贝克”、“德国汉堡”、“德国不莱梅”、“德国汉诺威”、“德国卡塞尔”、“德国杜塞尔多夫”、“德国科隆”、“德国圣奥古斯丁”、“德国波恩”、“德国威斯巴登”、“德国法兰克福”、“德国曼海姆”、“德国卡尔斯鲁厄”、“德国巴登巴登”、“德国斯图加特”、“德国慕尼黑”“德国纽伦堡”、“德国德累斯顿”、“德国莱比锡”、“德国柏林”、“瑞士巴塞尔”];
var定向服务;
函数初始化(){
directionsService=new google.maps.directionsService();
}
//让DirectionService计算两个城市之间的距离。
函数getDistance(i,j){
var请求={
来源:城市[i],
目的地:城市[j],
travelMode:google.maps.travelMode.DRIVING
};
var location1=城市[i];
var location2=城市[j];
路由(请求、功能(响应、状态){
if(status==google.maps.directionstatus.OK){
var距离=0;
对于(var i=0;iYou错误地标记了此问题。您的代码没有使用Google Maps Javascript API v3,而是使用了已弃用并已关闭的Google Maps Javascript API v2。请勿将该版本的API用于新代码。
<script type="text/javascript">
//city array
var cities = ["Rostock,Germany", "Lubeck,Germany", "Hamburg,Germany", "Bremen,Germany", "Hannover,Germany", "Kassel,Germany", "Dusseldorf,Germany", "Koln,Germany", "St. Augustine,Germany", "Bonn,Germany", "Wiesbaden,Germany", "Frankfurt,Germany", "Mannheim,Germany", "Karlsruhe,Germany", "Baden Baden,Germany", "Stuttgart,Germany", "Munich,Germany", "Nurnberg,Germany", "Dresden,Germany", "Leipzig,Germany", "Berlin,Germany", "Basel,switzerland"];
var directionsService;
function initialize() {
directionsService = new google.maps.DirectionsService();
}
// Let directionsService calculate the distance between two cities.
function getDistance(i, j) {
var request = {
origin: cities[i],
destination: cities[j],
travelMode: google.maps.TravelMode.DRIVING
};
var location1 = cities[i];
var location2 = cities[j];
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var distance = 0;
for(var i=0; i<response.routes[0].legs.length; ++i) {
distance += response.routes[0].legs[i].distance.value;
}
//var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = distance / 1000;
document.getElementById('results').innerHTML += location1 + "; " + location2 +" " + drivingDistanceKilometers + ' km</br>';
}
});
}
function showDistances() {
// loop over all cities. Skip directions between twice the same city
for(var i=0; i<5 && i<cities.length; i++) {
for(var j=i; j<5 && j<cities.length; j++) {
if(i==j) {
// skip
}
else {
getDistance(i,j);
}
}
}
}
</script>
<body onload="initialize()">
<form action="#" onsubmit="showDistances(); return false;">