Restrict google autocomplete output to city only - javascript

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;
}
}
});
}

Related

Google maps api autocomplete show only street and street number

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.

Google Geochart - same countries, different values

I got some problems with displaying values for a country. The thing is, I want to display where football players of a certain team come from. Because many of them have same nationality, geochart displays only the last name in the array when hoovering over the country, but I want it to display all the names.
This is the code:
var chart = function (item) {
body = document.getElementById("regions_div");
body.innerHTML = " ";
var places = [];
var names = [];
for (var i = 0; i<item.length; i++) {
person = item[i];
country = person.nationality;
name = person.name;
places.push(country);
names.push(name);
};
console.log(places);
console.log(names);
google.charts.load('upcoming', {'packages':['geochart']});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = [];
var header = ["Country", "Name"];
data.push(header);
for (var i = 0; i < places.length; i++) {
var temp = [];
temp.push(places[i]);
temp.push(names[i]);
console.log(temp);
data.push(temp);
}
console.log(data);
var chartdata = google.visualization.arrayToDataTable(data);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(chartdata, options);
}
}
And the screenshot, for example this time has multiple players from England but only the last one in the array is displayed :
Thanks for help!
following is an example of building a custom tooltip to show all names at each country
the group() method is used to group the names by country
then the tooltip is updated for each row in chartdata
for all the names found for each country
see following working snippet...
google.charts.load('current', {
callback: drawRegionsMap,
packages:['geochart']
});
function drawRegionsMap() {
var container = document.getElementById('regions_div');
container.innerHTML = '';
var names = ["Sam Johnstone", "Chris Smalling", "Phil Jones", "Luke Shaw"];
var places = ["United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom"];
var data = [];
var header = ["Country", "Name"];
data.push(header);
for (var i = 0; i < places.length; i++) {
var temp = [];
temp.push(places[i]);
temp.push(names[i]);
data.push(temp);
}
var chartdata = google.visualization.arrayToDataTable(data);
// group data by country, name
var groupdata = google.visualization.data.group(
chartdata,
[0, 1],
[{
aggregation: google.visualization.data.count,
column: 1,
label: "Name",
type: "number"
}]
);
// update tooltip for each chart data row
for (var i = 0; i < chartdata.getNumberOfRows(); i++) {
// find group rows for current country
var locationRows = groupdata.getFilteredRows([{
column: 0,
value: chartdata.getValue(i, 0)
}]);
// build tooltip of all names for current country
var nameTooltip = '';
locationRows.forEach(function (index) {
if (nameTooltip !== '') {
nameTooltip += ', ';
}
nameTooltip += groupdata.getValue(index, 1);
});
// update tooltip
chartdata.setValue(i, 1, nameTooltip);
}
var chart = new google.visualization.GeoChart(container);
chart.draw(chartdata);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div"></div>

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

Google Map Condition on Town

I want a condition on my code where user input start point and end point, I want to make a check on start point to check that it is located in London or not so I find this code which work well in function but I want its variable town make function outside of this function so I create the checkpoint.
var input = document.getElementById('start');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
// get town of selected place
function getTown(address_components) {
var geocoder = new google.maps.Geocoder(); result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
var town = getTown(place.address_components);
// if place is in London, move marker to the place
if (town == 'London') {
alert('in London');
} else {
// if not, do nothing and alert user
alert('you must click on a place in London');
}
});
How can I access var town outside of this function on whole page so I make condition on base of it?
You can make a variable outside of the scope of the callback to set the result to.
var input = document.getElementById('start');
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {lat: 51.507351, lng: -0.127758}
});
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var town;
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
function getTown(address_components) {
result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
document.getElementById('place').innerHTML = '';
document.getElementById('town').innerHTML = '';
town = getTown(autocomplete.getPlace().address_components);
});
function inLondonCheck(placeName) {
document.getElementById('place').innerHTML = placeName + " in London? " + (town === 'London');
document.getElementById('town').innerHTML = town || '';
}
setInterval(function() {
if (town) inLondonCheck(autocomplete.getPlace().name);
}, 500);
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<input id="start">
<div>Place<pre id="place"></pre></div>
<div>Town<pre id="town"></pre></div>
<div id="map-canvas"></div>

FOR loop to iterate through array

I have an array that I would like to iterate through with a for loop to avoid excessive code. I would like to take the following:
var mySchool = document.getElementById(varID[0]);
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
and have it be more like:
for(var i=0; i < varID.length; i++){
var mySchool = document.getElementById(varID[i]);
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
}
I've been doing some reading and i suspect it has something to do with Javascript closures but can't for the life of me get it to work with the various code examples i have found. I'm hoping the experienced eye can spot something i'm missing from this Javascript newbie.
My complete code looks like this:
//There are more items in my array but i wanted to keep it short here
var varID = [
"adamRobertson",
"blewett",
"brentKennedy"
];
var tableId = '1yc4wo1kBGNJwpDm6e-eJY_KL1YhQWfftjhA38w8';
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(49.491052,-117.304484),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer();
filterMap(layer, tableId, map);
//Trying to get this to work
for(var i=0; i < varID.length; i++){
var mySchool = document.getElementById(varID[i]);
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
}
//Trying to avoid this 25 times
/*
google.maps.event.addDomListener(document.getElementById(varID[0]),
'click', function() {
filterMap(layer, tableId, map);
});
*/
}
// Filter the map based on checkbox selection.
function filterMap(layer, tableId, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: 'Location',
from: tableId,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var schools = document.getElementsByName('school');
for (var i = 0, school; school = schools[i]; i++) {
if (school.checked) {
var schoolName = school.value.replace(/'/g, '\\\'');
filter.push("'" + schoolName + "'");
}
}
var where = '';
if (filter.length) {
where = "School IN (" + filter.join(',') + ')';
}
return where;
}
google.maps.event.addDomListener(window, 'load', initialize);
The HTML basically contains input for checkboxes to turn my polygons on and off.
Thanks in advance for any help.
I think it will help if you change the code to this:
var mySchool; var limit = varID.length;
for(var i=0; i < limit; i++){
mySchool = document.getElementById(varID[i]);
(function(){
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
}());
}
I took the for limit calculation out of the loop so that will save some speed too.
I haven't used the maps api so you may have to add some arguments to the closure.
var mySchool; var limit = varID.length;
for(var i=0; i < limit; i++){
mySchool = document.getElementById(varID[i]);
(function(s, l, t, m){
google.maps.event.addDomListener(s,'click', function() {
filterMap(l, t, m);
});
}(mySchool, layer, tableId, map));
}
I'm not sure which args are needed, but you'll probably figure it out.

Categories

Resources