简体   繁体   中英

Get country name during google map creation

What is the best way to obtain country name during creation of Google Map to update country name field in real time?

I create my Google Map with this code:

function createMap(address,distance){
        address=$("#settingMeetingPrefs_meeting_city").val();
        distance=$("#settingMeetingPrefs_meeting_distance").val();

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

            if (address == null)
                var address =  "{{city}}";
            else
                var address = address;

             if (distance==null)
                    distance= "{{distance}}";

            geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

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


                            var latlng = new google.maps.LatLng(latitude, longitude);
            var myOptions = {
                zoom: 7,
                center: latlng,
                scrollwheel: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

                            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });


                            // Add circle overlay and bind to marker
                            var circle = new google.maps.Circle({
                            map: map,
                            radius: distance * 1000 ,
//                              radius: document.getElementById('distance').value * 1000 ,    // 10 miles in metres
                            fillColor: '#0000FF'
                            });
                            circle.bindTo('center', marker, 'position');


                                 }
                            }); 

}

The country is stored in the geocoding result address component . To get the country you could do something like this

while (i<results[0].address_components.length){
  if(results[0].address_components[i].types[0]=='country'){
  console.log(results[0].address_components[i].short_name);
}

i++;

}//end while

more info here Geocoding Strategies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM