Why is this variable undefined or not returned?

前端 未结 2 657
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 03:33

I have the following code:

/*
 * converts a string to geolocation and returns it
 */

function stringToLatLng(string){
    if(typeof string == \"string\"){
              


        
相关标签:
2条回答
  • 2021-01-26 03:54

    Something like this:

    function stringToLatLng(strloc, callback){
        if(typeof string == "string"){
            geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': strloc}, function(results, status) {
               if (status == google.maps.GeocoderStatus.OK) {
                  callback.call({}, results[0].geometry.location);
               } else {
                  console.log("Geocode was not successful for the following reason: " + status);
               }
            });
       }
    }
    
    stringToLatLng('New York', function(pos){
        console.log(pos);
    });
    

    In your code, when you return, you are actually returning from the function(results, status){..} function, not the stringToLatLng function, as said in the comments its an asynchronous call, so you must use a callback.

    0 讨论(0)
  • 2021-01-26 04:09
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    

    ref: Javascript geocoding from address to latitude and longitude numbers not working

    0 讨论(0)
提交回复
热议问题