Google geocode is late (still one step behind)

前端 未结 1 1181
野的像风
野的像风 2021-01-29 11:55

I put there my whole code. Trying to determine location address. My script should create still one marker with geocoded address (in console - variable kktina).

But, unfo

相关标签:
1条回答
  • 2021-01-29 12:28

    You can't do this:

      function geocodePosition(pos) {
        geocoder.geocode({
          latLng: pos
        }, function(responses) {
          if (responses && responses.length > 0) {
            address = responses[0].formatted_address;
          } else {
            address = 'Cannot determine address at this location.';
          }
        });
        return address;
      }
    

    the Geocoder is asynchronous, the value of address is undefined when it is returned.

    Use the returned data inside the callback function instead, something like this (not tested):

    var kktina = null;
    function geocodePosition(pos) {
      geocoder.geocode({
        latLng: pos
      }, function(responses) {
        if (responses && responses.length > 0) {
          kktina = responses[0].formatted_address;
        } else {
          kktina = 'Cannot determine address at this location.';
        }
       console.log(kktina);
        var marker = new google.maps.Marker({
          position: point,
          draggable: true
        });
        markers.push(marker)
        marker.setMap(map);
      });
    }      
    
    0 讨论(0)
提交回复
热议问题