2016-11-17 4 views
-1

У меня проблема в моем коде google api. Проблема в том, что я использовал геокодирование в bootstrap modal, при первом клике, когда я заполнил входы, которые у меня есть информация в консоли: не могу прочитать свойство null. Вот пример моего кода:Google maps API геокодирование - Невозможно прочитать свойство null

var location1; 
var location2; 
function licz() { 
     var geocoder = new google.maps.Geocoder(); 

     if (geocoder) { 
      geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        location1 = results[0].geometry.location; 
        console.log(location1); 

       } else { 
        alert("Geocode was not successful for the following reason: " + status); 
       } 
      }); 
      geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        location2 = results[0].geometry.location; 
        console.log(location2); 

       } else { 
        alert("Geocode was not successful for the following reason: " + status); 

      latlng = new google.maps.LatLng((location1.lat() + location2.lat())/2, (location1.lng() + location2.lng())/2); 



      var mapOptions = { 
       center: latlng, 
       zoom: 15, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 

      directionsService = new google.maps.DirectionsService(); 
      directionsDisplay = new google.maps.DirectionsRenderer(
      { 
       suppressMarkers: true, 
       suppressInfoWindows: true 
      }); 
      directionsDisplay.setMap(map); 
      var request = { 
       origin: location1, 
       destination: location2, 
       travelMode: google.maps.DirectionsTravelMode.DRIVING 
      }; 
      directionsService.route(request, function (response, status) { 
       if (status == google.maps.DirectionsStatus.OK) { 
        directionsDisplay.setDirections(response); 
        distance = response.routes[0].legs[0].distance.text; 
        document.getElementById("txtDistance").value = distance; 
       } 
      }); 

      var marker1 = new google.maps.Marker({ 
       map: map, 
       position: location1, 
       title: "Start" 
      }); 

      var marker2 = new google.maps.Marker({ 
       map: map, 
       position: location2, 
       title: "Koniec" 
      }); 

     } 
var geocoder = new google.maps.Geocoder(); 

     if (geocoder) { 
      geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        location1 = results[0].geometry.location; 
        console.log(location1); 

       } else { 
        alert("Geocode was not successful for the following reason: " + status); 
       } 
      }); 
      geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        location2 = results[0].geometry.location; 
        console.log(location2); 

       } else { 
        alert("Geocode was not successful for the following reason: " + status); 
       } 
      }); 

     } 

Функция licz() обрабатывается OnClick в кнопки на модальном так:

<button type="button" runat="server" id="btnLicz" class="btn btn-info" onclick="licz();">Calculate</button> 

Когда я нажимаю снова проблема решена.

Может ли кто-то из вас рассказать мне, что я делаю неправильно?

Спасибо за помощь!

+1

где ошибка? – n00dl3

+0

Когда я первый раз нажимаю кнопку, сообщение об ошибке «location1 is undefined» или «location1 не может прочитать свойство null» Извините, но я не на своем компьютере прямо сейчас – k1dl3r

+1

Пока неясно, так как в вашем коде есть много ссылок на location1. Когда вы вернетесь на свой компьютер, укажите точную строку, в которой ошибка выдается в вашем коде. – n00dl3

ответ

1

geocoder.geocode() Звонки асинхронны. Это значит, когда вы звоните:

latlng = new google.maps.LatLng((location1.lat() + location2.lat())/2, (location1.lng() + location2.lng())/2); 

location1 еще не определено.

Чтобы избежать этого, вы должны создать что-то вроде этого:

geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
    location1 = results[0].geometry.location; 
    geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     location2 = results[0].geometry.location; 
     latlng = new google.maps.LatLng((location1.lat() + location2.lat())/2, (location1.lng() + location2.lng())/2); 
     } else { 
     alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    } else { 
    alert("Geocode was not successful for the following reason: " + status); 
    } 
}); 

Однако есть более элегантные способы справиться с такой ситуацией, как и обещания (функция ES6, но существуют библиотеки):

var location1; 
var location2; 

function geocode(data){ 
    return new Promise((resolve,reject)=>{ 
    geocoder.geocode(data, (results, status) => { 
     if (status == google.maps.GeocoderStatus.OK) 
     resolve(results[0].geometry.location); 
     else 
     reject(); 
    }); 
    }) 
} 
var asyncs=[ 
    geocode({ 'address': document.getElementById('txtMiasto1').value }).then(result=>location1=result), 
    geocode({ 'address': document.getElementById('txtMiasto2').value }).then(result=>location2=result) 
] 
Promise.all(asyncs).then(()=>{ 
    //do stuffs with location1 and location2 
}).catch(()=>{ 
    //handle errors 
}) 

Обратите внимание, что этот код будет работать в современном браузере (который поддерживает функции стрелок и обещания, такие как Chrome и Firefox), но вы можете заменить функцию стрелки простым старым function(){} и использовать библиотеку обещаний, такую ​​как this one (первый результат google, никогда тэ sted)