2015-11-24 3 views
1

Я пытаюсь использовать HTML 5 GeoLocation, чтобы получить долготу и широту, а затем использовать API Карт Google , чтобы получить код страны этой долготы/широты. Есть ли более простой способ получить код страны из google places api?Как получить код страны из Google Places API

Я нашел решение по этой ссылке ==>Getting country code from Google Maps and HTML 5 GeoLocation , чтобы получить код страны.

Есть ли способ получить код страны непосредственно из google places api, не получив сначала широту и долготу, а затем перейдя на google maps api.

Это следующий скрипт, который я использую, чтобы получить код страны из API Google Адресов

<script> 
// This example displays an address form, using the autocomplete feature 
// of the Google Places API to help users fill in the information. 

var placeSearch, autocomplete; 
var componentForm = { 
street_number: 'short_name', 
route: 'long_name', 
locality: 'long_name', 
administrative_area_level_1: 'short_name', 
country: 'long_name', 
postal_code: 'short_name' 
}; 

function initAutocomplete() { 
    // Create the autocomplete object, restricting the search to geographical 
// location types. 
    autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement}  */(document.getElementById('autocomplete')), 
    {types: ['(cities)']}); 

    // When the user selects an address from the dropdown, populate the address 
    // fields in the form. 
    //autocomplete.addListener('place_changed', fillInAddress); 

// Get Latitude and longitude 

    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
     var place = autocomplete.getPlace(); 
     //document.getElementById('city2').value = place.name; 
     document.getElementById('lat').value = place.geometry.location.lat(); 
     document.getElementById('lng').value = place.geometry.location.lng(); 

    }); 
} 

// [START region_fillform] 
function fillInAddress() { 
// Get the place details from the autocomplete object. 
var place = autocomplete.getPlace(); 

    for (var component in componentForm) { 
    document.getElementById(component).value = ''; 
    document.getElementById(component).disabled = false; 
    } 

    // Get each component of the address from the place details 
// and fill the corresponding field on the form. 
for (var i = 0; i < place.address_components.length; i++) { 
    var addressType = place.address_components[i].types[0]; 
    if (componentForm[addressType]) { 
    var val = place.address_components[i][componentForm[addressType]]; 
    document.getElementById(addressType).value = val; 
    } 
    } 
    } 
    // [END region_fillform] 

</script> 
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&callback=initAutocomplete" 
    async defer></script> 

ответ

5

Чтобы получить код страны, получить короткое имя компонента адреса с типом country:

// for the country, get the country code (the "short name") also 
if (addressType == "country") { 
    document.getElementById("country_code").value = place.address_components[i].short_name; 
} 

фрагмент кода:

// This example displays an address form, using the autocomplete feature 
 
// of the Google Places API to help users fill in the information. 
 

 
function fillInAddress() { 
 
    // Get the place details from the autocomplete object. 
 
    var place = autocomplete.getPlace(); 
 

 
    for (var component in componentForm) { 
 
    document.getElementById(component).value = ''; 
 
    } 
 

 
    // Get each component of the address from the place details 
 
    // and fill the corresponding field on the form. 
 
    for (var i = 0; i < place.address_components.length; i++) { 
 
    var addressType = place.address_components[i].types[0]; 
 
    if (componentForm[addressType]) { 
 
     var val = place.address_components[i][componentForm[addressType]]; 
 
     document.getElementById(addressType).value = val; 
 
    } 
 
    // for the country, get the country code (the "short name") also 
 
    if (addressType == "country") { 
 
     document.getElementById("country_code").value = place.address_components[i].short_name; 
 
    } 
 
    } 
 
} 
 

 
var placeSearch, autocomplete; 
 
var componentForm = { 
 
    locality: 'long_name', 
 
    administrative_area_level_1: 'short_name', 
 
    country: 'long_name', 
 
}; 
 

 
function initAutocomplete() { 
 
    // Create the autocomplete object, restricting the search to geographical 
 
    // location types. 
 
    autocomplete = new google.maps.places.Autocomplete(
 
    /** @type {!HTMLInputElement}  */ 
 
    (document.getElementById('autocomplete')), { 
 
     types: ['(cities)'] 
 
    }); 
 

 
    // When the user selects an address from the dropdown, populate the address 
 
    // fields in the form. 
 
    // Get Latitude and longitude 
 
    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
 
    var place = autocomplete.getPlace(); 
 
    document.getElementById('lat').value = place.geometry.location.lat(); 
 
    document.getElementById('lng').value = place.geometry.location.lng(); 
 
    fillInAddress(); 
 
    }); 
 
} 
 
google.maps.event.addDomListener(window, 'load', initAutocomplete);
html, 
 
body { 
 
    height: 100%; 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
#map { 
 
    height: 100%; 
 
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script> 
 
<div id="locationField"> 
 
    <input id="autocomplete" placeholder="Enter your address" type="text" /> 
 
</div> 
 
<table id="address"> 
 
    <tr> 
 
    <td class="label">City</td> 
 
    <td class="wideField" colspan="3"> 
 
     <input class="field" id="locality" disabled="true" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td class="label">State</td> 
 
    <td class="slimField"> 
 
     <input class="field" id="administrative_area_level_1" disabled="true" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td class="label">Country</td> 
 
    <td class="wideField" colspan="2"> 
 
     <input class="field" id="country" disabled="true" /> 
 
    </td> 
 
    <td class="label">Country Code</td> 
 
    <td class="shortField"> 
 
     <input class="field" id="country_code" disabled="true" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td class="label">latitude</td> 
 
    <td class="wideField" colspan="3"> 
 
     <input class="field" id="lat" disabled="true" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td class="label">longitude</td> 
 
    <td class="wideField" colspan="3"> 
 
     <input class="field" id="lng" disabled="true" /> 
 
    </td> 
 
    </tr> 
 
</table>

+0

Кто-нибудь знает, если 'zipcode' отличается от адресов_компонентов, которые можно было бы извлечь из места автозаполнения? – italiansoda

+0

Ах, отвечая на мой вопрос. Его называют 'postal_code', а не zipcode. – italiansoda

0

Наконец получил решение, чтобы получить код страны в Google Search API. Этот код может помочь кому-то.

<script> 
// This example displays an address form, using the autocomplete feature 
// of the Google Places API to help users fill in the information. 

var placeSearch, autocomplete; 
var componentForm = { 
    street_number: 'short_name', 
    route: 'long_name', 
    locality: 'long_name', 
    administrative_area_level_1: 'short_name', 
    country: 'long_name', 
    postal_code: 'short_name', 
    political: 'short_name' 
}; 

function initAutocomplete() { 
    // Create the autocomplete object, restricting the search to geographical 
    // location types. 
    autocomplete = new google.maps.places.Autocomplete(
     /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')), 
     {types: ['(cities)']}); 

    // When the user selects an address from the dropdown, populate the address 
    // fields in the form. 
    autocomplete.addListener('place_changed', fillInAddress); 
} 

// [START region_fillform] 
function fillInAddress() { 
    // Get the place details from the autocomplete object. 
    var place = autocomplete.getPlace(); 

    for (var component in componentForm) { 
    document.getElementById(component).value = ''; 
    document.getElementById(component).disabled = false; 
    } 

    // Get each component of the address from the place details 
    // and fill the corresponding field on the form. 
    for (var i = 0; i < place.address_components.length; i++) { 
    var addressType = place.address_components[i].types[0]; 
    if (componentForm[addressType]) { 
     var val = place.address_components[i][componentForm[addressType]]; 
     if(place.address_components[i][componentForm['political']]){ 
      console.log(place.address_components[i][componentForm['country']]); 
      if(isNaN(place.address_components[i][componentForm['political']])){ 
       country_code=place.address_components[i][componentForm['political']]; 
       var country_name=place.address_components[i][componentForm['country']]; 
      } 
     } 
     document.getElementById(addressType).value = val; 

    } 
    } 
    // **Country code, Country name goes here** 
    document.getElementById("Country_code").value=country_code; 
    document.getElementById("Country_name").value=country_name; 
    console.log('Country Code='+country_code+', Country Name='+country_name); 
} 
// [END region_fillform] 

    </script> 
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&callback=initAutocomplete" 
     async defer></script> 
0
<?php 
$address = '77-379 North End road, London London SW61NP, United Kingdom'; // Your address(Please USe exist address) 
$prepAddr = str_replace(' ','+',$address); 

$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=AIzaSyDUpz-WEZ7r24PPkGKEuyqBd9VsPPVPcQk&sensor=false'); 
$output= json_decode($geocode); 


if (isset($output->results)) { 
    if (isset($output->results[0])) { 
     if (isset($output->results[0]->address_components)) { 
      foreach ($output->results[0]->address_components as $key => $value) { 
       if (isset($value->types)) { 
        if (isset($value->types[0])) { 
         if($value->types[0] == 'country'){ 
          print_r($value->short_name); //GB 
         } 
        } 
       } 
      } 
     } 
    } 
} ?> 
Смежные вопросы