How to add Google Maps Autocomplete search box?

I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible.

My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and some tutorials yet they all bundle together the autocomplete functionality with mapping it on an embedded Google map.

I don't need to map the location visually, I just need the autocomplete box for now, unfortunately I cannot work out which parts of the API are relevant to this and every example I have looked at includes plenty of JS for mapping.

How can I ONLY add the autocomplete input functionality?

241440 次浏览

A significant portion of this code can be eliminated.

HTML excerpt:

<head>
...
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>
<body>
...
<input id="searchTextField" type="text" size="50">
...
</body>

Javascript:

function initialize() {
var input = document.getElementById('searchTextField');
new google.maps.places.Autocomplete(input);
}


google.maps.event.addDomListener(window, 'load', initialize);
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<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 initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
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]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]


// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]


</script>


<style>
#locationField, #controls {
position: relative;
width: 480px;
}
#autocomplete {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
.label {
text-align: right;
font-weight: bold;
width: 100px;
color: #303030;
}
#address {
border: 1px solid #000090;
background-color: #f0f0ff;
width: 480px;
padding-right: 2px;
}
#address td {
font-size: 10pt;
}
.field {
width: 99%;
}
.slimField {
width: 80px;
}
.wideField {
width: 200px;
}
#locationField {
height: 20px;
margin-bottom: 2px;
}
</style>
</head>


<body onload="initialize()">
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"></input>
</div>




</body>
</html>

Just copy and paste the sameple code below.

<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
</head>
<body>
<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">


<script>
function init() {
var input = document.getElementById('locationTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}


google.maps.event.addDomListener(window, 'load', init);
</script>
</body>
</html>

Well formatted code can be found from this link. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.

HTML

<input id="searchInput" class="controls" type="text" placeholder="Enter a location">

JavaScript

<script>
function initMap() {
var input = document.getElementById('searchInput');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>

Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(poenter code heresition) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}

To use Google Maps/Places APIs now, you're required to use an API Key. So the API URL will change from

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>

to

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});


function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}
<input id="autocomplete" placeholder="Enter your address" type="text"/>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://mapenter code heres.googleapis.com/maps/api/js?key=AIzaSyC7vPqKI7qjaHCE1SPg6i_d1HWFv1BtODo&libraries=places"></script>
<script type="text/javascript">
function initialize() {


new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
}


initialize();


</script>

To get latitude and longitude too, you can use this simple code:

<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>

<input type="text"required id="autocomplete">


<script>
function initAutocomplete() {
new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{types: ['geocode']}
);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
async defer></script>

Follow the below code.

Add this to your TS file.

declare this, top of your class.

declare var google;

declare the view child for Map and the input.

@ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
@ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;

this method is run on ngOnInit() event or ngAfterViewInit() event.

autoComplete() {
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
center: {lat: -33.8688, lng: 151.2093},
zoom: 7
});


const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById('infowindow-content');


infowindow.setContent(infowindowContent);


const marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
autocomplete.addListener('place_changed', () => {
infowindow.close();
marker.setVisible(false);
const place = autocomplete.getPlace();


let cus_location = {
lat: place.geometry.location.lat(),
long: place.geometry.location.lng()
}


console.log('place data :................', cus_location);
localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));


if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: ' + place.name );
return;
}


if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);  // Why 17? Because it looks good.
}


marker.setPosition(place.geometry.location);
marker.setVisible(true);
let address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}


if(infowindowContent){
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
}


infowindow.open(map, marker);
});


}

calling the method on ngAfterViewInit.

ngAfterViewInit(): void {
this.autoComplete();
}

And this is the HTML code. please modify as per your need.

<ion-content fullscreen>
<div class="location-col">




<div class="google-map">
<!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
<div #mapElement id="map"></div>
</div>




<div class="location-info">
<h2>Where is your car located?</h2>
<p>Enter address manually or click location detector icon to use current address.</p>
<div class="form-group">


<div class="location-row">
<input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
<span class="location-icon" (click)="getCurrentLocation()">
<img src="../../assets/images/location-icon.svg" alt="">
</span>
</div>


<button type="button" class="location-search-btn" (click)="goToVendorSearch()">
<i class="fa fa-angle-right"></i>
</button>


</div>
</div>
</div>
</ion-content>

I am currently using the Google API to retrieve the location that the user enters in the form/ input. I'm also using an angular function that showing the current location and suggests a city name pin code etc... - add google API index.html.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&libraries=geometry,places"></script>
- add id in input box to get string & charcters.
<input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)">
- and create function on your component.ts file.
import these file

import * as _ from 'lodash';
declare var google: any;
 checkAddress(value) {
if (!value) {
this.model.location = _.cloneDeep(value);
this.rfpForm.controls['location'].setValue(this.model.location);
}
}
initLocationAutocomplete() {
let autocomplete, place;
const getLocation = () => {
place = autocomplete.getPlace();
if (place && (place.formatted_address || place.name)) {
// if you want set value in your form controls like this
this.model.location = _.cloneDeep(place.formatted_address || place.name);
// YourFormName.controls['location'].setValue(this.model.location);
// YourFormName.controls['location']['_touched'] = true;
}
};
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
autocomplete.addListener('place_changed', getLocation);
}

So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:

HTML:

<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">

JS:

<script>
function initMap() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById("address").value = JSON.stringify(place.address_components);
});
}
</script>


<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>