Skip to content Skip to sidebar Skip to footer

How Can I Get Just City And State From The Google Maps API?

I want to remove the country from the Google API map search.For example I don't want Atlanta,GA,USA but I want something like Atlanta,GA. Is this possible? Here is my code. The fo

Solution 1:

I am trying to do the exact same thing... (not show the ', USA' at the end of every city, State entry)

It's funny because I believe it used to work this way out of the box... see this old screenshot in the developer docs here: https://developers.google.com/maps/documentation/javascript/places-autocomplete#map_controls enter image description here

However if you go to their example it does not work this way: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-hotelsearch enter image description here

Look you thought that Input field was long enough for any city right? wrong: enter image description here

Here is my approach using MutationObserver to remove the Country every time! This approach is inspired by this other stackoverflow post: JS: event listener for when element becomes visible?

Update: this now works with IE (I have tested IE, Edge, Firefox, Chrome)

<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Test</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
    </style>
  </head>

  <body>

    <div id="findhotels">
      Find City State:
    </div>

    <div id="locationField">
      <input id="autocomplete" placeholder="Enter a city" type="text" />
    </div>

    <script>

      var autocomplete;
	  var addressEle = document.getElementById('autocomplete');
	  var dropdown;
	  var times = 0;
	  
      function initAutocomplete() {
        
        // Create the autocomplete object and associate it with the UI input control.
        // Restrict the search to the default country, and to place type "cities".
        autocomplete = new google.maps.places.Autocomplete(
            (addressEle), {
              types: ['(cities)'],
              componentRestrictions: {'country': 'us'}
            });
			
        autocomplete.addListener('place_changed', onPlaceChanged);
      }
	  
	  function initAutoObserver(){
		dropdown = document.querySelector('div.pac-container.pac-logo');
		if( dropdown){
			if(times){ console.log( 'IE sucks... recursive called '+times+' times.' ); }
		  //Literally the ONLY listener google gives us is the 'place_changed' Listener
		  //So we are having to use a MutationObserver to detect when the dropdown is shown/hidden 
		  //When Dropdown changes, remove ', USA'
			var observer = new MutationObserver(function(){
			   if(dropdown.style.display !='none' ){
					//console.log('is visible');
					for(var i=0,l=dropdown.children.length; i<l; i++){ 
						var thespan = dropdown.children[i].lastElementChild
						thespan.innerHTML = thespan.innerHTML.replace(', USA','');
					}
			   } else {
					//console.log('is hidden');
					//console.log(addressEle.value);
					addressEle.value = addressEle.value.replace(', USA','');
			   }
			});
			observer.observe(dropdown,  { attributes: true, childList: true });
		}else {
			//IE seems to take longer to add the dropdown element to the dom:
			times++;
			setTimeout( initAutoObserver, 20);
		}
	  }
	  window.addEventListener("load", initAutoObserver );

      // When the user selects a city, get the place details for the city
      function onPlaceChanged() {
        var place = autocomplete.getPlace();
        if (place.geometry) {
			//console.log(place);
        } else {
			addressEle.placeholder = 'Enter a city';
        }
      }
	  
	//Prevent Numbers (Allow Only Letters) from Being entered into the City, State Field:
    addressEle.addEventListener('input', function (event) {
        this.value = this.value.replace(/[^a-zA-Z -,]/g, "");
    });
	
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCvRwR3-fGr8AsnMdzmQVkgCdlWhqUiCG0&libraries=places&callback=initAutocomplete"
        async defer></script>
  </body>
</html>

Post a Comment for "How Can I Get Just City And State From The Google Maps API?"