2015-05-31 5 views
0

Меня интересуют адреса геокода на стороне клиента https://developers.google.com/maps/articles/geocodestrat#client Я нашел код кода на этом сайте http://opengeocode.org/tutorials/googlemap/googlemaps_6.php#example_6, и я попытался изменить его, чтобы достичь своей цели. Проблема в том, что я получаю только первый адрес. Что не так?Геокодирование двух или более адресов

<!DOCTYPE html> 
<html> 
<head> 
    <title>Google Map Template with Geocoded Address</title> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <!-- Google Maps API --> 
    <script> 
    var map; // Google map object 

    // Initialize and display a google map 
    function Init() 
    { 
     // Create a Google coordinate object for where to initially center the map 
     var latlng = new google.maps.LatLng(38.8951, -77.0367); // Washington, DC 

     // Map options for how to display the Google map 
     var mapOptions = { zoom: 12, center: latlng }; 

     // Show the Google map in the div with the attribute id 'map-canvas'. 
     map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
    } 

    // Update the Google map for the user's inputted address 
    function UpdateMap() 
    { 
     var geocoder = new google.maps.Geocoder(); // instantiate a geocoder object 
     var destinationGeocoder = new google.maps.Geocoder(); 

     // Get the user's inputted address 
     var address = document.getElementById("address").value; 
     var destination = document.getElementById("destination").value; 

     // Make asynchronous call to Google geocoding API 
     geocoder.geocode({ 'address': address }, function(results, status) { 
      var addr_type = results[0].types[0]; // type of address inputted that was geocoded 
      if (status == google.maps.GeocoderStatus.OK) 
       ShowLocation(results[0].geometry.location, address, addr_type); 
      else  
       alert("Geocode was not successful for the following reason: " + status);   
     }); 

     destinationGeocoder.geocode({ 'destination': destination }, function(results, status) { 
      var addr_type = results[0].types[0]; // type of address inputted that was geocoded 
      if (status == google.maps.GeocoderStatus.OK) 
       ShowLocation(results[0].geometry.location, destination, addr_type); 
      else  
       alert("Geocode was not successful for the following reason: " + status);   
     }); 
    } 

    // Show the location (address) on the map. 
    function ShowLocation(latlng, add, addr_type) 
    { 
     // Center the map at the specified location 
     map.setCenter(latlng); 

     // Set the zoom level according to the address level of detail the user specified 
     var zoom = 12; 
     switch (addr_type) 
     { 
     case "administrative_area_level_1" : zoom = 6; break;  // user specified a state 
     case "locality"      : zoom = 10; break;  // user specified a city/town 
     case "street_address"    : zoom = 15; break;  // user specified a street address 
     } 
     map.setZoom(zoom); 

     // Place a Google Marker at the same location as the map center 
     // When you hover over the marker, it will display the title 
     var marker = new google.maps.Marker({ 
      position: latlng,  
      map: map,  
      title: address 
     }); 

     // Create an InfoWindow for the marker 
     var contentString = "" + address + ""; // HTML text to display in the InfoWindow 
     var infowindow = new google.maps.InfoWindow({ content: contentString }); 

     // Set event to display the InfoWindow anchored to the marker when the marker is clicked. 
     google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); 
    } 

    // Call the method 'Init()' to display the google map when the web page is displayed (load event) 
    google.maps.event.addDomListener(window, 'load', Init); 

    </script> 
    <style> 
    /* style settings for Google map */ 
    #map-canvas 
    { 
     width : 500px; /* map width */ 
     height: 500px; /* map height */ 
    } 
    </style> 
</head> 
<body> 
    <!-- Dislay Google map here --> 
    <div id='map-canvas' ></div><br/> 
    <div> 
     <label for="address"> Address:</label> 
     <input type="text" id="address"/> 
     <label for="destination"> Destination:</label> 
     <input type="text" id="destination"/> 
     <button onclick="UpdateMap()">Locate</button> 
    </div> 
</body> 
</html> 

Более того: если я поменять функцию два геокодирования я не получаю никакого результата, я не могу объяснить, почему

+0

Как вы производите свой код это вопрос? Просьба представить [Минимальный, полный, проверенный и читаемый пример] (http://stackoverflow.com/help/mcve), который демонстрирует вашу проблему. Я получаю две ошибки javascript с кодом как отправленный 'Uncaught InvalidValueError: неизвестный объект назначения 'и' Uncaught InvalidValueError: setTitle: not a string' – geocodezip

ответ

1

Существует ошибка в коде в destinationGeocoder вы должны использовать address вместо destination свойство геокод всегда address

destinationGeocoder.geocode({ 'address': destination }, function(results, status) { 
     var addr_type = results[0].types[0]; // type of address inputted that was geocoded 
     if (status == google.maps.GeocoderStatus.OK) 
      ShowLocation(results[0].geometry.location, destination, addr_type); 
     else  
      alert("Geocode was not successful for the following reason: " + status);   
    }); 
1

Я получаю две ошибки JavaScript с кодом, как писал.

  • Uncaught InvalidValueError: unknown property destination.
    Это неверно:

    destinationGeocoder.geocode({ 
        'destination': destination 
    }, 
    

должен быть (нет destination варианта для GeocoderRequest object:.

destinationGeocoder.geocode({ 
     'address': destination 
    }, 

Если я это исправить, я получаю оба маркера

working fiddle

  • Uncaught InvalidValueError: SETTITLE: не строка

Это один потому, что это неправильно:

var marker = new google.maps.Marker({ 
     position: latlng, 
     map: map, 
     title: address 
    }); 

Там нет адрес переменной в функции ShowLocation, должно быть:

var marker = new google.maps.Marker({ 
     position: latlng, 
     map: map, 
     title: add 
    }); 

fixed fiddle

Смежные вопросы