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
Related
I tried to no avail to get HTML, CSS and Javascript to limit number of items in datalist, for whatever reason, it is isn't working. The list is populated by a loop on a array.
<datalist id="trainNoList">
<script>
if (markers)
{
var options = '';
var trainNoList = [];
for (var i = 0; i < markers.length; i++) {
var trainNo = markers[i][20];
trainNoList.push(trainNo);
options += "<option value='" + trainNoList[i] + "'></option>";
}
}
</script>
</datalist>
<!-- Use JavaScript to pan to the train when an option is selected -->
<script>
$("#trainNoInput").on("input", function() {
var selectedTrainNo = $(this).val();
// Check if the input is a range
var rangeCheck = selectedTrainNo.split("-");
if (rangeCheck.length === 2) {
vehiclestart = rangeCheck[0];
vehicleend = rangeCheck[1];
} else {
// Perform the same actions as in the original code
for (var i = 0; i < markers.length; i++) {
var trainNo = markers[i][20];
if (trainNo == selectedTrainNo) {
var lat = parseFloat(markers[i][2]);
var lng = parseFloat(markers[i][3]);
var setcontentforpopup = "Vehicle"+markers[i][0]+"";
vehiclestart = 1;
vehicleend = 99999999999999;
var popup = L.popup()
.setLatLng([lat, lng])
.setContent(setcontentforpopup)
.addTo(map);
map.flyTo([lat, lng], 16);
break;
}
}
}
});
$("#trainNoInput").on("focus", function() {
console.debug("The trainNoInput field has received a keyup event");
clearTimeout(ajaxtimeout);
});
$("#trainNoInput").on("blur", function() {
ajaxtimeout = setTimeout(foo, 10000);
console.debug("no");
});
$("#trainNoInput").on("keyup", function(event) {
if (event.keyCode === 13) {
markerLookup = {};
markerClusters.clearLayers();
foo();
}
});
</script>
enter image description here
The desire result is simple - limit number of items shown down to 5 or whatever set amount and add a scroll bar to scroll down to see the remainder of the records
enter image description here
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®ion=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;
}
}
});
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to make google map with filtering. One filter is select box (for now it is working) and other filer is with check boxes. So now my it have behavior as a radio button. You can se example here http://extrol.ellectadigital.com/distributeri/.
When you check it, it shows good pin, but when you click on the second it removes the first pin, and I don't want that.
So here is my code :
`http://codepen.io/PoznanM/pen/VpoZOm`
Problem is here onclick="filterChecker(this.value);" in filterChecker function only single checked item was compared and other marker are cleared.
So you have to compare all the checked items. I added function selectAllChecked() which passes checked values as array to function filterChecker()
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var filters = {
shower: false,
vault: false,
flush: false
}
// Our markers
markers1 = [
['0', 'Title', 44.741318, 20.433573, 'Beograd', 'distributer'],
['1', 'Title', 45.823783, 16.024404, 'Zagreb', 'servis'],
['2', 'Title', 44.438350, 17.631215, 'Bosna', 'maloprodaja']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(45.662477, 18.022074);
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.662477, 18.022074),
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var tip = marker[5];
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
tip: tip,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
var get_set_options = function() {
ret_array = []
for (option in filters) {
if (filters[option]) {
ret_array.push(option)
}
}
return ret_array;
}
var filter_markers = function() {
set_filters = get_set_options()
// for each marker, check to see if all required options are set
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// start the filter check assuming the marker will be displayed
// if any of the required features are missing, set 'keep' to false
// to discard this marker
keep = true
for (opt = 0; opt < set_filters.length; opt++) {
if (!marker.properties[set_filters[opt]]) {
keep = false;
}
}
marker.setVisible(keep)
}
}
// Fuction for checkboxes
var tipovi = document.getElementsByClassName('chk-btn').value;
var selectAllChecked = function() {
var checkedPlace = []
var allCheckedElem = document.getElementsByName('filter');
for (var i = 0; i < allCheckedElem.length; i++) {
if (allCheckedElem[i].checked == true) {
checkedPlace.push(allCheckedElem[i].value)//creating array of checked items
}
}
filterChecker(checkedPlace) //passing to function for updating markers
}
var filterChecker = function(tip) {
//console.log(tip);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
//console.log(marker);
if (in_array(this.marker.tip, tip) != -1) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
#map-canvas {
height: 300px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<div id="map-canvas">
</div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Izaberite Mesto</option>
<option value="Beograd">Beograd</option>
<option value="Zagreb">Zagreb</option>
<option value="Bosna">Bosna</option>
</select>
<div id="buttons">
<input type="checkbox" name="filter" value="distributer" class='chk-btn' onclick="selectAllChecked();">
<label for='shower'>Distributer</label>
<input type="checkbox" name="filter" value="maloprodaja" class='chk-btn' onclick="selectAllChecked();">
<label for='flush'>Maloprodaja</label>
<input type="checkbox" name="filter" value="servis" class='chk-btn' onclick="selectAllChecked();">
<label for='vault'>Servis</label>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmUfKutqGZ-VgbD4fwjOFd1EGxLXbxcpQ&sCensor=false"></script>
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>
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.