0

Я пытаюсь принять адрес в цикле for и получить широту и долготу этого адреса и создать маркер с значениями lat/long.Google maps Геокодер и маркер не работают

У меня есть преобразование адреса в lat/long, но я не могу получить «новый маркер», чтобы принимать значения.

Любые предложения?

   var latitude; 
       var longitude; 
       var myLatLng; 

       for (i = 0; i < locations.length; i++) { 

        var geocoder = new google.maps.Geocoder(); 
        var BuisAddress = locations[i][1]; 
        geocoder.geocode({ 'address': BuisAddress }, function (results, status) { 
         if (status == google.maps.GeocoderStatus.OK) { 
          latitude = results[0].geometry.location.lat(); 
          longitude = results[0].geometry.location.lng(); 
          } 
         }); 


        myLatLng = new google.maps.LatLng(latitude, longitude); 
        marker = new google.maps.Marker({ 
         position: myLatLng, 
         map: map 
        }); 

**** первый UPDATE ****

, если я сделаю это, то только один маркер появляется, когда у меня есть несколько адресов и маркер всплывающее не работает. Если я сделаю следующее, то появятся все три маркера, но все же не будут работать с кликабельными всплывающими окнами.

    var geocoder = new google.maps.Geocoder(); 
        BuisAddress = locations[i][1]; 
        geocoder.geocode({ 'address': BuisAddress }, function (results, status) { 
          if (status == google.maps.GeocoderStatus.OK) { 
            latitude = results[0].geometry.location.lat(); 
            longitude = results[0].geometry.location.lng(); 
            myLatLng = new google.maps.LatLng(latitude, longitude); 
            marker = new google.maps.Marker({ 
             position: myLatLng, 
             map: map 
            }); 
           } 
          }); 


        myLatLng = new google.maps.LatLng(latitude,longitude); 
        marker = new google.maps.Marker({ 
         position: myLatLng, 
         map: map 
        }); 



        google.maps.event.addListener(marker, 'click', (function(marker, i) { 
         return function() { 
          var str = encodeURI(locations[i][1]).replace(",", ""); 
          var address = str.replace(/%20/g, "+"); 
         var infowindow = new google.maps.InfoWindow(); 
+0

Геокодер является асинхронным. Вы должны ** использовать ** возвращенный результат в функции обратного вызова. – geocodezip

+0

Связанный вопрос: [Многоадресный массив Google maps Uncaught TypeError: Не удается прочитать свойство «0» неопределенного] (http://stackoverflow.com/questions/32318578/multi-address-array-google-maps-uncaught-typeerror-cannot -read-property-0-of) – geocodezip

+0

Связанный вопрос: [Сопоставление нескольких местоположений с API API Google Maps v3 и API геокодирования] (http://stackoverflow.com/questions/29463131/mapping-multiple-locations-with-google- maps-javascript-api-v3-and-geocoding-api) – geocodezip

ответ

0

Если кто-то интересно, как я это сделал, вот оно!

function geocodeAddress(locations, i) { 
    var title = locations[i][0]; 
    var address = locations[i][1]; 
    var url = locations[i][2]; 
    var latitude; 
    var longitude; 
    geocoder.geocode({ 
     'address': locations[i][1] 
    }, 

    function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      latitude = results[0].geometry.location.lat(); 
      longitude = results[0].geometry.location.lng(); 
     var marker = new google.maps.Marker({ 
      icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png', 
      map: map, 
      position: results[0].geometry.location, 
      title: title, 
      animation: google.maps.Animation.DROP, 
      address: address, 
      url: url, 
      latitude: latitude, 
      longitude: longitude 
     }) 
     infoWindow(marker, map, title, address, url, latitude, longitude); 
     bounds.extend(marker.getPosition()); 
     map.fitBounds(bounds); 
     } else { 
     alert("geocode of " + address + " failed:" + status); 
     } 
    }); 
} 

function infoWindow(marker, map, title, address, url, latitude, longitude) { 
    google.maps.event.addListener(marker, 'click', function() { 
     var html ="html code here..."; 
    iw = new google.maps.InfoWindow({ 
     content: html, 
     maxWidth: 350 
    }); 
    iw.open(map, marker); 
    }); 
} 

function createMarker(results) { 
    var marker = new google.maps.Marker({ 
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png', 
    map: map, 
    position: results[0].geometry.location, 
    title: title, 
    animation: google.maps.Animation.DROP, 
    address: address, 
    url: url 
    }) 
    bounds.extend(marker.getPosition()); 
    map.fitBounds(bounds); 
    infoWindow(marker, map, title, address, url); 
    return marker; 
} 
0

Вы можете попробовать этот способ (я добавил вектор маркер для управления коллекцией вектор)

var latitude; 
    var longitude; 
    var myLatLng; 

    myMarker = [] 
    for (i = 0; i < locations.length; i++) { 

     geocoder.geocode({ 'address': BuisAddress }, function (results, status) { 
           if (status == google.maps.GeocoderStatus.OK) { 
             latitude = results[0].geometry.location.lat(); 
             longitude = results[0].geometry.location.lng(); 
             myLatLng = new google.maps.LatLng(latitude, longitude); 
             marker[i] = new google.maps.Marker({ 
              position: myLatLng, 
              map: map 
             }); 
            } 
           }); 

     google.maps.event.addListener(marker[i], 'click', (function(marker[i], i) { 
           return function() { 
            var str = encodeURI(locations[i][1]).replace(",", ""); 
            var address = str.replace(/%20/g, "+"); 
            var infowindow = new google.maps.InfoWindow(); 
           } 
     })); 

    } 
+0

Не совсем работает см. 1-й обновленный комментарий выше. –

+1

Вы посмотрели на любой из связанных вопросов? – geocodezip

+0

Уважение к первому вопросу, я вижу больше кода. Я наблюдал только за тем, что маркер не может быть установлен за пределами функции обратного вызова для геокодирования. Затем у вас есть цикл для нескольких местоположений и листер, который отображает информационные окна для каждого маркера. Правильно? – scaisEdge