Javascript geocoding from address to latitude and longitude numbers not working

前端 未结 3 1407
故里飘歌
故里飘歌 2020-12-04 17:41

I\'m using the following geocoding function to convert a textual address into latitude and longitude numbers, but it\'s not working right. The alert writes \"undefined\".

3条回答
  •  情书的邮戳
    2020-12-04 17:52

    Try using this instead:

    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    

    It's bit hard to navigate Google's api but here is the relevant documentation.

    One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

    $.each(results[0].address_components, function(){
        $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
    });
    

    What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
    If you're only interrested in the whole formated address then you can follow Google's example

提交回复
热议问题