How to restrict google map autocomplete - javascript

Question 1) I'm attempting to search for an postcode (UK) via autocomplete code below
For example, if I search for
NE237AP- this is what I get
Annitsford Drive, Dudley, Cramlington NE23 7AP, UK
But the postcode is omitted if I search street name
Annitsford Drive - I get
Annitsford Drive, Annitsford, Cramlington, UK
Why is that.
Question 2) How can I just use the Postcode results from above into another text box.
Question 3) Is there a way to restrict to UK - seen many snippets of code but none of them seem to work, with the code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=key&libraries=places"></script>
<script>
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var input = document.getElementById('autocomplete_search');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
// place variable will have all the information you are looking for.
$('#lat').val(place.geometry['location'].lat());
$('#long').val(place.geometry['location'].lng());
});
}
</script>
<title>Google Places Autocomplete InputBox Example Without Showing Map - Tutsmake.com</title>
<style>
.container{
padding: 10%;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12"><h2>Google Places Autocomplete InputBox Example Without Showing Map</h2></div>
<div class="col-12">
<div id="custom-search-input">
<div class="input-group">
<input id="autocomplete_search" name="autocomplete_search" type="text" class="form-control" placeholder="Search" />
<input type="hidden" name="lat">
<input type="hidden" name="long">
</div>
</div>
</div>
</div>
</div>
</body>
</html>

You are not getting the postcode detail because the address Annitsford Drive, Annitsford, Cramlington, UK itself is actually covered by multiple post codes such as NE23 7AP,NE23 7AX, etc.
You can refer to the sample code here that fetches the data and populates it in an address form. Note that you may need to change the components in the sample above to cater the address formats in the corresponding region.
As per this documentation:
Use the componentRestrictions option to restrict the autocomplete search to a particular country.
In your case, inside your initialize function, you can use the lines below to restrict the autocomplete predictions to UK:
var input = document.getElementById('autocomplete_search');
var options = {
componentRestrictions: {country: 'gb'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

Related

Autocomplete for address using Google Maps JavaScript API

I came across a challenge and I kindly needed your help. I was developing form input with one of the fields being address / location. I wanted to harness Google Maps API, with services such as AutoComplete and Address Geocoding. I have HTML and JS files. My main issue is that I wanted to tap invalid addresses that users might type and alert them that it is an error. Like for instance, if someone types an address that has not been suggested or types incomplete address, I should be able to tell them that it is not a valid address. This works but only when I press enter, and not submit. If I press submit, it submits the form and doesn't notify.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places">
function initMap() {
const input = document.getElementById("location-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
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 + "'");
swal("Please fill all the *Required fields","Click okay to continue", "warning");
return;
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="form.css">
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Libre+Franklin&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly" defer></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
<!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
<title>Document</title>
</head>
<body>
<form action="" id="mform">
<div class="container">
<div class="row">
<!--Address Section-->
<div id="pac-container">
<input id="location-input" type="text" placeholder="Enter a location" />
</div>
<!--End of Address Section-->
<!--Form Submit Section-->
<div class="row fill-form">
<input name="submit" type="submit" id="submit" class="submit" value="Submit">
</div>
<!--End of Form Submit Section-->
</div>
</div>
<script src="places.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</form>
</body>
</html>
I have tried adding an submit event listener, but I cannot get what I expect
You need to first prevent the form from submitting and check place.geometry the way you check it on place_changed event. Show that nice swal message and then do whatever you want to if it's valid.
Here below is your own codes edited and checked before submit.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places">
function initMap() {
const input = document.getElementById("location-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
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 + "'");
swal("Please fill all the *Required fields","Click okay to continue", "warning");
return;
}
});
//Check before submit
document.getElementById('mform').addEventListener('submit', function(e){
e.preventDefault(); //prevent form submit
const place = autocomplete.getPlace(); //get place from autocomplete
if (!place.geometry) { //check if valid location
swal("Please fill all the *Required fields","Click okay to continue", "warning");
return;
}
});
}

Set Postcode/ZIP From Google Auto Complete

I am attempting code that when I enter an address in to a text box it shows the address then shortens to only postcode - much like gif below..
Came across this link but does not seem to work - but on the right lines
https://www.aspforums.net/Threads/647425/Set-Postal-Code-in-TextBox-from-Google-Place-Autocomplete-result-selection-using-JavaScript/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=key&libraries=places"></script>
<script>
google.maps.event.addDomListener(window, 'load', initialize);
function initialize()
{
var input = document.getElementById('autocomplete_search');
var options =
{
componentRestrictions: {country: 'gb'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
var input = document.getElementById('autocomplete_search');
//var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
// place variable will have all the information you are looking for.
$('#lat').val(place.geometry['location'].lat());
$('#long').val(place.geometry['location'].lng());
});
}
</script>
<title>Google Places Autocomplete InputBox Example Without Showing Map - Tutsmake.com</title>
<style>
.container{
padding: 10%;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12"><h2>Google Places Autocomplete InputBox Example Without Showing Map</h2></div>
<div class="col-12">
<div id="custom-search-input">
<div class="input-group">
<input id="autocomplete_search" name="autocomplete_search" type="text" class="form-control" placeholder="Search" />
<input type="hidden" name="lat">
<input type="hidden" name="long">
</div>
</div>
</div>
</div>
</div>
</body>
</html>
When entering an address such Nevile Road, it does not show postcode (and that's all I want). Is there a way to get the postcode from the autocomplete address.
It's not currently possible to filter Place Autocomplete predictions on postcodes only. Take a look at this open feature request in Google's Issue Tracker.
But you can choose to display only the postcode for a selected place in the search box, instead of the full address. In your example, you could change the place_changed listener as follows:
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
$('#lat').val(place.geometry['location'].lat());
$('#long').val(place.geometry['location'].lng());
let postcode;
for (let i = 0; i < place.address_components.length; i++) {
let types = place.address_components[i].types;
for (let type of types) {
if (type === "postal_code") {
postcode = place.address_components[i].long_name;
}
}
}
if (!postcode) {
postcode = place.formatted_address;
}
$('#autocomplete_search').val(postcode);
});
Working jsfiddle (add your API key to run it).
With the above code implementation, now if you type in "Nevile Road" into the text field, and select the first place prediction, Nevile Road, Salford, UK, you'll get its postal_code_prefix as the only value, i.e. M7.
Likewise, if you start typing a full postcode, e.g. "M7 3PP", you'll get a Nevile Road, Salford M7 3PP, UK place suggestion, and selecting it will give you M7 3PP.
However, note that this won't always work as there are many addresses that don't have a single, specific postcode. E.g. "London, UK" won't return any postcode at all (as it obviously can't).
Hope this helps!

Google Sheets Script Sidebar button not activating function

I've spent hours trying to figure this out, since I feel like I should do that before asking a question here. Searched, looked at answers, tried stuff. I think I learn that way and expand my skills/knowledge.
At any rate, I'm trying to just get started using a sidebar to make my sheets script app work better, and testing in small pieces. I want the Clear Old button (at this point) to simply open an alert box with the date in it, fed from a text box generated by datePicker.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
<base target="_top">
</head>
<body>
<p><strong>Clear Old Entries</strong></p>
<p>Clear Entries before</p>
<p><input type="text" id="datepicker"></p>
<p><input type="submit" value="Clear Old" onClick="google.script.run.ClearOld(document.getElementById(datepicker).value)" /></p>
<p><input type="button" value="Close Sidebar" onClick="google.script.host.close()" /></p>
</body>
</html>
And here is the script code that gets the menu item and the sidebar, as well as the function I'm trying to use as a short term test:
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Bulletinator')
.addItem('Create Bulletin', 'bulletinatorSidebar')
.addItem('Clear Old', 'clearOldSideBar')
.addToUi();
}
function bulletinatorSidebar() {
var html = HtmlService.createHtmlOutputFromFile('BullV2Side')
.setTitle('Bulletinator')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
function clearOldSideBar() {
var html = HtmlService.createHtmlOutputFromFile('ClearOldSide')
.setTitle('Clear Old Entries')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
var today;
var todayDay;
var todayDate;
var ui = SpreadsheetApp.getUi();
var sh = SpreadsheetApp.getActiveSheet();
var rg = sh.getDataRange();
var vA = rg.getValues();
var rowsFound = 0;
var rowsDeleted = 0;
function ClearOld(value) {
var clearDate=value;
var testThis = ui.alert(
'Clear entries prior to',
clearDate,
ui.ButtonSet.YES_NO);
When I click the button in the sidebar there is no response, and nothing shows up in the execution transcript.
On a side note, I also struggled with being able to have two datePickers in the sidebar; only one worked. So that is why this setup has two separate sidebars getting called.
Thanks for any help.
It seems, the datepicker variable is not defined. you have to use the next code
onClick="google.script.run.ClearOld(document.getElementById('datepicker').value)"
or
onClick="google.script.run.ClearOld($('#datepicker').val())"

How do I use Google's AutoComplete locations API?

In my HTML I added
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
and in my Javascript I've added
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
where location is the ID of my searchbox. When I try to type in a value, there's just a gray exclamation mark at the top and it doesn't allow me to type anything more than one letter.
You can use following example.
function initialize() {
new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
}
initialize();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<input id="autocomplete" placeholder="Enter your address" type="text"></input>
Here is a snippet example:
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDR924KH0p6IDMCsOaG5rMmEo17JSl5K2U&libraries=places"></script>
<script type="text/javascript" src=""></script><!-- ← link to javascript file-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>Location:</div>
<input type="text" id="location" name="location" value="" autocomplete="off" />
</body>
</html>
Note:
It took some time for the API key to be valid but once the API connection works the page will work as well. You might need to refresh the page a few times though as it seems that the API key was having problems connecting at first.
Source: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete

Get Element Breaking Code

I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?

Categories

Resources