Google maps api autocomplete show only street and street number - javascript

Now in my input I prints street, street number, state, country..
How can I print only street and street number?
My code:
var options = {
types: ['geocode']
};
var input = document.getElementById('address');
autocomplete = new google.maps.places.Autocomplete(input, options);

You could solve this by overwriting the input's value once a place was selected.
var input = document.getElementById("address");
var autocomplete = new google.maps.places.Autocomplete(input, {types: ["geocode"]});
autocomplete.addListener("place_changed", function() {
var placeResult = autocomplete.getPlace();
var addressComponents = placeResult.address_components;
var street = "";
var number = "";
// loop through addressComponents and find the route and street_number types
for (var i = 0, i_len = addressComponents.length; i < i_len; i++) {
var addressType = addressComponents[i].types[0];
switch(addressType) {
case "route":
street = addressComponents[i]["long_name"];
break;
case "street_number":
number = addressComponents[i]["long_name"];
break;
}
}
input.value = number + " " + street;
});
I recently created a jQuery plugin that will easily allow you to do this. This would be your new code:
$("#address").geocomplete({
fields: {
"#address" : "street address"
}
});
The plugin will allow you to autofill any number of fields based on the results of the selected place. It also adds custom styling, provides callbacks and fixes an annoying scrolling issue.

Related

Changing location of html element dynamically using javascript

I am trying to change the pixel location of an html element using JavaScript. My function should take in a user input for the location and change the pixel coordinates according to an array.
This function should create a button at the user inputted location, but nothing happens. I think the issue is with setting a style attribute that requires both a text string and the variable that stores the location string. Any help would be appreciated.
var arr = [
["A1", "left:81px;"],
["A2", "left:145px;"]
]
function moveObject(arr) {
var location = prompt("Enter location", "A1");
var i;
for (let i = 0; i < arr.length; i++) {
if (arr[i][0] === location) {
destination = arr[i][1] + ";";
}
}
var box = document.createElement("button");
box.setAttribute("style", "position: absolute;");
box.setAttribute("style", destination)
box.innerText = location;
document.body.appendChild(box);
}
moveObject(arr)
Combine the css value strings and only call setAtrribute('style') once.
The second call wipes out the first
You are also adding an extra ; when it already exists in the value in your array.
Note I have not added any validation that the user entered value exists in the array. You will need to do that yourself before adding undefined values in the style
var arr = [
["A1", "left:81px;"],
["A2", "left:145px;"]
]
function moveObject(arr) {
var location = prompt("Enter location", "A1");
var i;
for (let i = 0; i < arr.length; i++) {
if (arr[i][0] === location) {
destination = arr[i][1] ;
}
}
var box = document.createElement("button");
// combine style values
box.setAttribute("style", "position: absolute;" + destination);
box.innerText = location;
document.body.appendChild(box);
}
moveObject(arr)
Several issues
I removed a stray " and added some text. Then I moved the left from the string and used the location as a lookup table instead
var arr = {
"A1": {"left":"81px"},
"A2": {"left":"145px"}
}
function moveObject(arr) {
var location = prompt("Enter location", "A1");
if (arr[location]) {
var box = document.createElement("button");
box.setAttribute("style", "position: absolute;");
var key = Object.keys(arr[location])
box.style[key] = arr[location][key]
box.innerText = location;
document.body.appendChild(box);
}
else alert("Location '"+location+"' not available")
}
moveObject(arr)

Restrict google autocomplete output to city only

I have the following code to look for cities from a given country using the google auto complete api:
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&sensor=false&libraries=places&region=uk" type="text/javascript"></script>
function initialize() {
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: { country: "uk" }
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
I have added region in the script src so as not to include the country in the output.
For example, if I type Lo, I get London only and not London, UK
However since I am getting the country, its ISO code, from a dropdown, I need to be able to change both the componentRestrictions and the region in the google api URL.
Any idea how to do that? I know I can get the country selected from the dropdown as below:
var country= $('#CountryDropdown');
How do I pass the var country to the componentRestrictions and the region?
I had the same problem and I solved it by this.
Hope this will help you.
<script src="https://maps.googleapis.com/maps/api/js?key=Yourkey&v=3.exp&libraries=places"></script>
function initialize() {
var input = document.getElementById('FullAddress');
var options = {
types: ['address'],
componentRestrictions: { country: 'uk' }
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// 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;
}
$("#Latitude").val(place.geometry.location.lat());
$("#Longitude").val(place.geometry.location.lng());
// 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;
}
}
});
}

Extract substring of e-mail message body to google spreadsheet

I'm using google app scripts to extract e-mail data into a google spreadsheet. I've got the below working code that I am trying to modify. I'm sure there's a smarter way ... but for now this works
function emf() {
var ss = SpreadsheetApp.getActiveSheet();
var label = GmailApp.getUserLabelByName("tkh_emf");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var name = messages[j].getPlainBody().split("Name*:")[1].split("\n")[0];
var email = messages[j].getPlainBody().split("E-mail*:")[1].split("\n")[0];
var phone = messages[j].getPlainBody().split("Phone:")[1].split("\n")[0];
var addr = messages[j].getPlainBody().split("Street Address:")[1].split("\n")[0];
var city = messages[j].getPlainBody().split("City*:")[1].split("\n")[0];
var find = messages[j].getPlainBody().split("hear about us?*:")[1].split("\n")[0];
var sub = messages[j].getSubject().split("Feedback via the ")[1].split("[")[0];
var num = messages[j].getSubject().split("Feedback via the ")[1].split("[")[1].split("]")[0];
var dat = messages[j].getDate();
var referrer = messages[j].getPlainBody().split("Referer URL:")[1].split("\n")[0];
ss.appendRow([name, email, phone, addr, city, find, sub, num, dat, referrer])
}
threads[i].removeLabel(label);
}
}
My e-mail looks like this:
Name*: name
E-mail*: email#gmail.com
Phone:
Street Address: 3704 17th St.
City*: city
How did you hear about us?*: Search engine results
Brief description of work requested*: work here
So my code extracts the appropriate strings for each field except the 'Phone' and 'Address' fields which are not required. If these fields are not filled, then the e-mail does not have the words 'Phone' or 'Street Address' so the lines for var phone and var addr fail because you can't split a null. Is there a way to insert an if string 'Phone' and 'Street Address' exists then execute the above? Thanks.
You were right that you'll need regex to accomplish the job (or it'll certainly make it easier). I've written a simple script in Codepen that'll show you how to use the regex.
In my script, I split the body data at the newline character, and then loop through the resulting array of lines. I pipe each line into a function that captures and returns the text you need. You needn't pipe in anything other the line--it detects what the name of the field is, and uses it appropriately, based on your current format.
In your own code, you would have to do the following to msg before placing it into your spreadsheet:
var msg = messages[j].getPlainBody();
var sub = messages[j].getSubject();
var dat = messages[j].getDate();
var bodyLines = msg.split("\n");
var fields = [];
for (var k = 0; k < bodyLines.length; k++) {
fields.push(getText(bodyLines[k]));
}
// do something with the resulting array of fields here
Here's the getText(str) function (can also be found in Codepen):
function getText(str) {
var fieldRe = new RegExp("(.+)\:", "g");
var fieldGroups = fieldRe.exec(str);
var fieldName = fieldGroups[1].split("*")[0];
fieldName = (fieldName == null) ? fieldGroups[1] : fieldName;
fieldName = fieldName.replace(/[\!\#\#\$\%\^\&\*\(\)\-\_\+\=\`\~\[\]\{\}\\\/\|\:\;\'\"\<\>\,\.\?]/g, function transformIllegal(x) {
return "\\" + x;
});
var re = new RegExp(`${fieldName}\\*?\\:\\s+(.*)`, "g");
var groups = re.exec(str);
var out = (groups == null) ? "" : groups[1];
return out;
}
Here's what I'm ending with. Not sophisticated but works.
function emf() {
var ss = SpreadsheetApp.getActiveSheet();
var label = GmailApp.getUserLabelByName("tkh_emf");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var name = messages[j].getPlainBody().split("Name*:")[1].split("\n")[0];
var email = messages[j].getPlainBody().split("E-mail*:")[1].split("\n")[0];
try {var phone = messages[j].getPlainBody().split("Phone:")[1].split("\n")[0];}
catch(e){var phone = "-";}
try {var addr = messages[j].getPlainBody().split("Street Address:")[1].split("\n")[0];}
catch(e){var addr = "-";}
var city = messages[j].getPlainBody().split("City*:")[1].split("\n")[0];
var find = messages[j].getPlainBody().split("hear about us?*:")[1].split("\n")[0];
try {var referrer = messages[j].getPlainBody().split("Referrer Name:")[1].split("\n")[0];}
catch(e){var referrer = "-";}
var sub = messages[j].getSubject().split("Feedback via the ")[1].split("[")[0];
var num = messages[j].getSubject().split("Feedback via the ")[1].split("[")[1].split("]")[0];
var dat = messages[j].getDate();
ss.appendRow([name, email, phone, addr, city, find, referrer, sub, num, dat])
}
threads[i].removeLabel(label);
}
}

Automatically send emails from addresses listed on one sheet when their name is selected from a drop down menu on another sheet

Hi I have a phone enquiry log that has two sheets - I want to automatically send emails to email addresses stored in a second sheet when their name is selected from a drop down box on another sheet.
I would also like to fill column H with a notifacation 'mail sent'but have limited skills as you all can probably see.
This is the code I have so far:
function emailMessage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var responses = ss.getSheetByName("Enquiry Log");
var lastRow = responses.getLastRow();
var values = responses.getRange("A"+lastRow)+":J"+(lastRow)).getValues(); //get the range and values in one step
var headers = responses.getRange("A1:J1").getValues();
var recipient = responses.getRange("E"+(lastRow)).getValues();
var emailSheet = ss.getSheetByName("Emails");
var names = emailSheet.getRange("A2:A12").getValues();
var emails = emailSheet.getRange("B2:B12").getValues();
var subject = "New phone message";
var message = composeMessage(headers,values);
var email = '';
for (var row=0; row < names.length; row++) {
if (names[row][0] == recipient) {
email = emails[row][0];
break;
MailApp.sendEmail(recipient,subject,message);
}
}
function composeMessage(headers,values) {
var message = 'Please check the Enquiry Log as you have a new message:'
for(var c=0;c<values[0].length;++c){
message+='\n'+headers[0][c]+' : '+values[0][c]
}
return(message);
}
};

Make Search Box GET Page on Enter

We want to make the following search box GET a page named /listings when a users types something in it and hits enter. Does anyone had any ideas on how to do this?
Many Thanks!
$(function() {
var autocomplete;
var geocoder;
var input = document.getElementById('location');
var options = {
componentRestrictions: {
'country': 'us'
},
types: ['(regions)'] // (cities)
};
autocomplete = new google.maps.places.Autocomplete(input, options);
$('#go').click(function() {
var location = autocomplete.getPlace();
geocoder = new google.maps.Geocoder();
console.log(location['geometry'])
lat = location['geometry']['location']['J'];
lng = location['geometry']['location']['M'];
var latlng = new google.maps.LatLng(lat, lng);
// http://stackoverflow.com/a/5341468
geocoder.geocode({
'latLng': latlng
}, function(results) {
for (i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].address_components.length; j++) {
for (var k = 0; k < results[i].address_components[j].types.length; k++) {
if (results[i].address_components[j].types[k] == "postal_code") {
zipcode = results[i].address_components[j].short_name;
$('span.zip').html(zipcode);
}
}
}
}
});
});
});
<input type="text" id="location" name="location" placeholder="City or ZIP Code" />
<span class="zip"></span>
The easiest way would be to register a listener for the change event on your input:
$('#location').change(function() {
$.get('./listings', function(data) {
// data is the content from '/listings'
});
});
If you want to load the contents from the listings page into a specific element, you can use jQuery.load:
$('#location').change(function() {
// loads the html content of listings into your element
// after the user changes the value of #location input
$( "your-element-selector" ).load("/listings");
});
Or if you want to navigate to the your-page/listings in the browser, you can take a look at this question

Categories

Resources