Google Map Condition on Town - javascript

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>

Related

Google maps api filter checkbox [closed]

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>

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

Javascript array element undefined in Google Maps API [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 8 years ago.
I am trying to add 3 markers to a map and when click on the markers, an info window will be shown. But every array element inside google.maps.event.addListener becomes undefined.
What's the problem?
<div id="map-canvas2" style="width:100%;height:500px"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var num;
var marker;
var infoWindow;
var infoText;
var lat;
var lng;
var map;
function initialize() {
num = 3;
marker = [];
infoWindow = [];
infoText = [];
lat = [];
lng = [];
infoText[0] = "test1";
lat[0] = 22.420845;
lng[0] = 114.208705;
infoText[1] = "test2";
lat[1] = 22.416026;
lng[1] = 114.209321;
infoText[2] = "test3";
lat[2] = 22.420841;
lng[2] = 114.205188;
for (var i = 0; i < num; i++) {
marker[i]=new google.maps.Marker({
position:new google.maps.LatLng(lat[i], lng[i]),
});
infoWindow[i] = new google.maps.InfoWindow({
content:"<div>"+infoText[i]+"</div>"
});
}
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(22.420458,114.207482)
};
map = new google.maps.Map(document.getElementById('map-canvas2'), mapOptions);
for (var i = 0; i < num; i++) {
marker[i].setMap(map);
google.maps.event.addListener(marker[i], 'click', function() {
new google.maps.InfoWindow({
content:"<div>"+infoText[i]+"</div>"
}).open(map,marker[i]);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The problem:
Each event listener is referencing the same variable i which gets incremented on each pass of the for loop. So after the loop is finished the value of i is 3, but none of your arrays have an index of 3 so you get undefined. Because each event handler is referencing the same i variable they are all referencing the same undefined array values.
The solution: Create a closure so that the event handler for each marker has a it's own variable instead sharing reference to single variable.
for (var i = 0; i < num; i++) {
marker[i].setMap(map);
google.maps.event.addListener(marker[i], 'click', (function(index) {
return function() {
new google.maps.InfoWindow({
content: "<div>"+infoText[index]+"</div>"
}).open(map, marker[index]);
}
})(i));
}
What we're doing is creating a Immediately-Invoked Function Expression "IIFE". The IIFE has a parameter called index which is set to the value of i. Because variables have function scope, index belongs only to this function. Inside the IIFE we return a function that will do the actual work when the event is triggered, but it will reference index not i.
Don't send indexed parameters to an anonymous function:
for (var i = 0; i < num; i++) {
var mrk = marker[i];
var iwContent = infoText[i];
mrk.setMap(map);
google.maps.event.addListener(mrk, 'click', function() {
new google.maps.InfoWindow({
content:"<div>"+iwContent+"</div>"
}).open(map,mrk);
});
}

Google Map One Infobox Open

I am building a directory, in this example it's a directory for doctors. I created a javascript array called "locations". The visitor can check checkboxes on the map to choose which kind of doctor should be displayed.
This is a sample of the array of locations to loop through in a for loop
var locations = [
[0, 'Total Care', 1, 0, 0, 0, 0, 0, 'Lake Elsinore', '92530', 'CA', 33.6603, -117.3830, '(951) 674-8779', 1],
... etc
];
This explains each key
locations[i][0] = business claimed or not (0 = unclaimed and 1 is claimed)
locations[i][1] = name
locations[i][2] = if general practitioner = 1, else = 0
locations[i][3] = if surgeon = 1, else = 0
locations[i][4] = if cardiologist = 1, else = 0
locations[i][5] = if urologist = 1, else = 0
locations[i][6] = if gynecologist = 1, else = 0
locations[i][7] = if pulmonologist = 1, else = 0
locations[i][8] = city
locations[i][9] = zip code
locations[i][10] = state
locations[i][11] = latitude
locations[i][12] = longitude
locations[i][13] = phone number
locations[i][14] = z-index
All works fine. I have a search function so the visitor can search by name. In the google map code below, I want to find a way to have the infoBox open on the marker of the doctor that was entered in the search function e.g.
if (locations[i][1] == "doctor name"){
code here }
I have been trying to find a solution for the past three days and can't find it, so I would really appreciate some help. This is the Google Map code:
var infoBox = null;
function initialize()
{
var centerMap = new google.maps.LatLng(33.6603, -117.3830);
var mapOptions = {zoom: 11,center: centerMap,mapTypeId: google.maps.MapTypeId.ROADMAP}
var map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
setMarkers(map, locations);
}
function setMarkers(map, markers)
{
var image = {url: 'images/marker.png',size: new google.maps.Size(17, 23),origin: new google.maps.Point(0,0),anchor: new google.maps.Point(8, 23)};
gpr = $('#check1').is(':checked') ? 1 : 0; // general practitioner
srg = $('#check2').is(':checked') ? 1 : 0; // surgeon
car = $('#check3').is(':checked') ? 1 : 0; // cardiologist
uro = $('#check4').is(':checked') ? 1 : 0; // urologist
gyn = $('#check5').is(':checked') ? 1 : 0; // gynecologist
pul = $('#check6').is(':checked') ? 1 : 0; // pulmonologist
for (var i = 0; i < markers.length; i ++)
{
var locations = markers[i];
var siteLatLng = new google.maps.LatLng(locations[11], locations[12]);
var boxText = document.createElement('div');
boxText.style.cssText = 'some styling';
link = locations[1].replace(' ','_');
link = link.toLowerCase();
// find out if this genre of doctor was searched for
setMarker = 0;
if (gpr == 1){if (locations[2] == 1){setMarker = 1;}}
if (srg == 1){if (locations[3] == 1){setMarker = 1;}}
if (car == 1){if (locations[4] == 1){setMarker = 1;}}
if (uro == 1){if (locations[5] == 1){setMarker = 1;}}
if (gyn == 1){if (locations[6] == 1){setMarker = 1;}}
if (pul == 1){if (locations[7] == 1){setMarker = 1;}}
// if one of the checkboxes was checked
if (setMarker == 1)
{
if (locations[0])
{
boxText.innerHTML = 'some html with link'; // claimed business
}
else
{
boxText.innerHTML = 'some html without link'; // unclaimed business
}
var infoBoxOptions = {content: boxText,disableAutoPan: false,maxWidth: 0,pixelOffset: new google.maps.Size(5, -80),zIndex: locations[14],boxStyle: {background: "url('images/tip.png') no-repeat",opacity: 0.9,width: "405px",height: "75px",border: '0px solid #900'},closeBoxMargin: "13px 5px 5px 5px",closeBoxURL: "images/close.gif",infoBoxClearance: new google.maps.Size(1, 1),isHidden: false,pane: "floatPane",enableEventPropagation: false};
var marker = new google.maps.Marker({position: siteLatLng,map: map,title: locations[1],zIndex: locations[14],icon: image,html: boxText});
google.maps.event.addListener(marker, 'click', function (e) {infoBox.setContent(this.html);infoBox.open(map, this);});
var infoBox = new InfoBox(infoBoxOptions);
}
}
}
Your help will be much appreciated. Thank you.
Unless I'm misunderstanding, you can just loop through your markers until the title matches the search text, and then open the appropriate info box on that marker. Something like:
$('#searchButton').click(function() {
var searchText = $('#searchBox').val();
for (var i = 0; i < markers.length; i++) {
if (markers[i].title.indexOf(searchText) > -1)
infoBoxes[i].open(map, markers[i]);
}
});
This example assumes you have two existing parallel arrays of markers and their corresponding info boxes.

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