javascript for循环打印同一组城市5次,而不是5个不同的城市集

时间:2014-10-22 23:21:47

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

我有一些javascript和html(下面)我试图遍历一系列城市,并使用谷歌地图API获取每个城市之间的距离当我在两个城市打字但我努力工作时我得到了这个工作在22个城市的数组中编码,每次显示相同的城市集,而不是两个城市的每个不同的集合以及它们之间的距离。

我猜这与时间有关,谷歌api的回报在某处覆盖了我的变量,但我无法弄清楚如何修复它。

现在,循环限制为3,以便在发生故障时节省时间。

预期产量: 罗斯托克,德国,吕贝克,德国200km 罗斯托克,汉堡100km 吕贝克,汉堡50km 汉堡,罗斯托克210km

我得到了什么: 汉堡,罗斯托克210km 汉堡,罗斯托克0km 汉堡,罗斯托克210km 汉堡,罗斯托克0km 汉堡,罗斯托克210km

我做错了什么?

<!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>

2 个答案:

答案 0 :(得分:0)

我看到的一个问题是在getDistance()函数中你正在使用全局变量。我会将它们声明为本地:

var location1 = {lat: ...
var location2 = {lat: ...

答案 1 :(得分:0)

你在for循环中放了一些东西,只需要做一次。 显然应该只调用initialize()一次。

我的代码是(类似的)你想要做的事情。请注意这一点:for(var j = i; ... j = i,你是不是两次计算距离(例如:Rostock-Lubeck和Lubeck-Rostock)。

一个大问题:当您在短时间内发送多个DirectionsService请求时,Google不喜欢它。 在我测试的地方,Google会在10个请求后停止。 也许请求之间的延迟可以解决这个问题(我必须检查)。

<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;">

...