logo
down
shadow

How to get the country code from Google Places API


How to get the country code from Google Places API

Content Index :

How to get the country code from Google Places API
Tag : javascript , By : chawei
Date : December 01 2020, 05:00 PM

I wish did fix the issue. To get the country code, get the short name of the address component with type 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>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to get all places (or specific type of place such as a restaurant) in a city or country with Google Places API?


Tag : development , By : littlefuzz
Date : March 29 2020, 07:55 AM
help you fix your problem Unfortunately you can't get more than 60 results from the Google Places API; at least not without breaking the terms of service:

Google Places componentrestrictions Country for iOS


Tag : javascript , By : Andrew
Date : March 29 2020, 07:55 AM
This might help you Do you have the latest version (1.11.0) of the Google Places API for iOS? This was added in that release (see the release notes).
With 1.11.0 this is done by setting the country property on GMSAutocompleteFilter.

Get country code from PlaceAutocompleteFragment android (Google Places API)


Tag : android , By : kema
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further With the Place object retrieved, you can get the Locale object associated :
Locale locale = place.getLocale();
locale.getCountry();
locale.getDisplayCountry();
LatLng coordinates = place.getLatLng(); // Get the coordinates from your place
Geocoder geocoder = new Geocoder(this, Locale.getDefault());

List<Address> addresses = geocoder.getFromLocation(
                coordinates.latitude,
                coordinates.longitude,
                1); // Only retrieve 1 address
Address address = addresses.get(0);
address.getCountryCode();
address.getCountryName();

retrieve points of interests (attractions/tourist places) of a place/country using google places api


Tag : json , By : Schmidt
Date : March 29 2020, 07:55 AM
hope this fix your issue Try this google places API url. You will get the point of interest/Attraction/Tourists places in (For Eg:) New York City. You have to use the CITY NAME with the keyword Point Of Interest
https://maps.googleapis.com/maps/api/place/textsearch/json?query=new+york+city+point+of+interest&language=en&key=API_KEY

Google Maps places API - How to get Country, Postal-code, Number, Website URL with Google map search box on multiple res


Tag : javascript , By : Manik
Date : March 29 2020, 07:55 AM
This might help you Google Maps places gives you a reference, and an ID. You can use that id to request extra details.
I added this to your code:
// make sure this variable is accesible where you need it (scope)
var service = new google.maps.places.PlacesService(map);
// request details
service.getDetails(place, function(result, status) {
  if (status !== google.maps.places.PlacesServiceStatus.OK) {
    console.error(status);
    return;
  }
  $('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>');
});
places.forEach(function (place) {
  ...
  <span id="website"></span>
  ...
}
<script>
    // This example adds a search box to a map, using the Google Place Autocomplete
    // feature. People can enter geographical searches. The search box will return a
    // pick list containing a mix of places and predicted search terms.
    function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: -33.8688,
                lng: 151.2195
            },
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        // Create the search box and link it to the UI element.
        var input = document.getElementById('searchInput');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
        });
        var markers = [];
        // srvice for PLACE details
        var service = new google.maps.places.PlacesService(map);
        // [START region_getplaces]
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function () {
            $('#mapContent').html("");
            var places = searchBox.getPlaces();
            if (places.length == 0) {
                return;
            }
            // Clear out the old markers.
            markers.forEach(function (marker) {
                marker.setMap(null);
            });
            markers = [];
            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function (place) {
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };
                // Create a marker for each place.
                var marker = new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                });
                google.maps.event.addListener(marker, 'click', function (evt) {
                    //document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6);
                    alert(this.placeId)
                });
                markers.push(marker);
                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
                $('#mapContent').append('<ul id="geoData">' +
                '<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+
                '<li>Postal Code: <span id="postal_code"></span></li>'+
                '<li>Country: <span id="country">'+  +'</span></li>'+
                '<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+
                '<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+
                '<li>Website: <span id="website"></span></li>'+
                '<li>Contact Number: <span id="number"></span></li>'+
                '<li>Rating: <span id="rating"></span></li>'+
                '</ul>');
        // request details
                service.getDetails(place, function(result, status) {
                  if (status !== google.maps.places.PlacesServiceStatus.OK) {
                    console.error(status);
                    return;
                  }
                  $('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>');
                });
            });
            map.fitBounds(bounds);
        });
        // [END region_getplaces]
    }
</script>
Related Posts Related QUESTIONS :
  • How do I pass an Event as a function parameter in HTML written inside JavaScript variable?
  • Interface of object parameter with default value and default property
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com