Loading specific markers by checkbox? - javascript

I am loading markers from a database to display on a google map by this below. This is working fine however, I would like to implement the option of pressing a particular button somewhere else on the page, and then map would dynamically change to only show markers pertaining to what was clicked.
Basically, I would like to filter by the 'type' column in my database but still keep all types loaing by default. eg. Page loads, Map loads and displays all types, User clicks on a button which causes the map to only show markers that have type1 as the value in the db. Kind of like a toggle with a check box.
Any ideas of how to go ahead with this, I don't think reloading markers from the db is the most efficient way, can I simply just hide markers which have this property?
map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
//Load Markers from the XML File, Check (map_process.php)
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
var description ='<p>'+ $(this).attr('description') +'</p>';
var point = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
var icon1 = customIcons[type] || {};
create_marker(point, name, address, false, false, false, icon1.icon);//"http://sanwebe.com/assets/google-map-save-markers-db/icons/pin_blue.png");
});
});

You can't just hide some specific markers according to their tag or type, you have to hide/remove them all first and then add those that you need on your map
Here are the functions that you need:
var all_markers = [];
var show_markers = [];
function setMarkers(map) {
for (var i = 0; i < show_markers.length; i++) {
show_markers[i].setMap(map);
}
}
function showMarkers(type) {
setMarkers(null);
show_markers = []
for (var i = 0; i < all_markers.length; i++) {
if (all_markers[i].type == type){
show_markers.push(all_markers[i])
}
}
setMarkers(map);
}
Here is the idea: Load all your markers into the all_markers, on your first loading the markers show_markers must be equal to all_markers. Hitting the button for showing specific markers must trigger function showMarkers which will clear your map and reload just specific ones.

Related

Zoom in to by name of location in openlayer 3

I'm trying to zoom in to location by name in sequence of state > district> village through dynamic select box.
In this one I have created two functions named zoomToExtDist(name) and zoomToExtVil(distname,vilname). But don't know they are not working. Which function we should use in openlayers 3. Can anyone tell me where I'm doing wrong.
Here's the plunker I have created zoom to location updated link
Please tell me which function we should use to set the view through lat long in openlayers 3 .
Thanks in advance :)
Try this
$(function() {
var records = jsonList.listval;
// console.log(records);
insert($('#state_id'), plucker(records, 'state'));
//------------------------^ grabs unique states
//--^ populate state list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value), 'district'));
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value), 'village'));
break;
}
case 'village':
{
zoomToExtDist($(this).val());
break;
}
}
});
function zoomToExtDist(name)
{ console.log(name);
for (var i = 0; i < jsonList.listval.length; i++)
{
if(name==jsonList.listval[i].village)
{
var tlon = parseFloat(jsonList.listval[i].longitude);
var tlat = parseFloat(jsonList.listval[i].latitude);
//var lonlat = new OpenLayers.LonLat(tlat,tlon);
map.getView().setCenter(ol.proj.fromLonLat([tlat, tlon]));
map.getView().setZoom(5);
}
}
}
....
http://plnkr.co/edit/Rja2b1dLsJm7FDFtlUJ0?p=preview
I cant comment because I don't have enough reputation, but in your plunkr I dont see the zoomtodist and zoomtovil functions? Which file are they in? Also, have you tried using the view.centerOn() [http://openlayers.org/en/v3.14.2/apidoc/ol.View.html#centerOn]? Or the view.setCenter() and view.setZoom() separately to perform the centring and zoom?

Store input value as a var and display it

This is the code I am working from:
http://jsfiddle.net/DYfbg/12/
If you click "map" then try typing a placename it gives you autocomplete suggestions. Then if you click on one of these suggestions it tells you the co-ordinates in an alert box.
What I want to do is capture what is in the input box when the autocomplete option is clicked, and then store it as a variable. Then in the alert box, along with the co-ordinates, I want to print the input box variable into it.
I know this all sounds pretty simple but I am new to javascript so I would really appreciate some input.
This is the segment of code:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
**// Store input box as variable**
if (!place.geometry) {
current_place = null;
alert('Cannot find place');
return;
} else {
current_place = place;
alert('Place is at:' + place.geometry.location);
**// Print input box varaible aswell**
} });
EDIT: This is as close as I could get without getting stuck:
// Set Autocomplete Location Variable equal to #loc input
$("#loc").val(ac_location);
// Print Autocomplete Variable
alert(ac_location);
In the "place" object returned with
var place = autocomplete.getPlace();
you have all info you need
Add a console.log and you'll see all infos returned.
For example:
var place = autocomplete.getPlace();
console.log(place);
window.myGlobalVar = place.name;
Edit based on notes below:
it seems original value of inputbox is actually stored in this property:
autocomplete.gm_accessors_.place.lf.d

Google Fusion Map - Dynamic Menu queried from the google fusion table

I am pretty sure that I know what the problem is with my code, but I am unsure how to fix it.
I have a google fusion table that i am querying to generate a menu that has radio buttons in it. A map that is a google fusion table visualized like a google map is also on the page.
When i hard code a couple radio buttons and click them it makes the items light up on the map based on the ID of the element. I using google.maps.event.addDomListener to make this magic work. So that works great.
Now i want to take it one step further and actually pull the data from a google fusion table so it shows the most up to date list of items i have in my table. So, I'm using jQuery and a $.get command to get the feed in jsonp. I'm outputting 2 columns of data and dynamically building radio buttons by attaching them with a innerHTML line -- attaching it to a div.
So, I'm thinking the problem has to do with the DOM, but i am not sure how to get the radio buttons to load in first and then load in the map so all is available to the maps events so clikcing the radio actually does something.
The question is what modifications do i need to make so my dynamic generated radio buttons will work with my google fusion map?
Here is my javascript code:
function initialize() {
var table = ########;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(30.6, -108.1),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer();
filterMap(layer, table, map);
getData(table);
google.maps.event.addDomListener(document.getElementById('num1'),
'click', function() {
filterMap(layer, table, map);
});
google.maps.event.addDomListener(document.getElementById('num2'),
'click', function() {
filterMap(layer, table, map);
});
}
// Filter the map based on checkbox selection.
function filterMap(layer, table, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: "State",
from: table,
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 bugs = document.getElementsByName('bug');
for (var i = 0, bug; bug = bugs[i]; i++) {
if (bug.checked) {
var BugName = bug.value.replace(/'/g, '\\\'');
filter.push("'" + BugName + "'");
}
}
var where = '';
if (filter.length) {
where = "'BugName' IN (" + filter.join(',') + ')';
}
return where;
}
// build the menu
function getData(table) {
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; // ? could be a function name
// write your SQL as normal, then encode it
var query = "SELECT BugName, bugAbbr FROM " + table + " LIMIT 1";
var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);
var jqxhr = $.get(queryurl, dataHandler, "jsonp");
}
function dataHandler(d) {
// get the actual data out of the JSON object
var data = d.table.rows;
var ftdata = ['<div>'];
for (var i = 0; i < data.length; i++) {
ftdata.push('<input type="radio" id="'+data[i][1]+'" value="'+data[i][0]+'" name="bug">'+data[i][0]+'');
}
ftdata.push('</div>');
document.getElementById('ft-data').innerHTML = ftdata.join('');
}
google.maps.event.addDomListener(window, 'load', getData);
google.maps.event.addDomListener(window, 'load', initialize);
This site had a bunch of example code.
http://csessig.wordpress.com/category/fusion-tables/

Event handler causes many alerts

I am working on a Phonegap app, in which I access device's contacts. I then store upto 10 contacts in window.localStorage. To do so, when the user select a button, I create a div which has three elements.
An image (contact icon that represents male/female contact)
The name of the contact
Another image (represents 'add' sign to add it to window.localStorage)
I then associate an event handler, which will first check if the contact already exists in the localStorage and then proceed to add the contact. Here is the code
function checkDuplicate(somevalue)
{
for(var i=0;i<10;i++) {
if(window.localStorage.getItem(i)!=null) {
if(window.localStorage.getItem(i)==somevalue) {
navigator.notification.alert('Entry exists at Button:'+i);
return false;
}
}
}
//chosenButton is a global variable
window.localStorage.setItem(chosenButton,somevalue);
document.getElementById('contactNumberField').textContent=somevalue;
}
//Problem is with the event listener attached to span2. Please read below
function addContact(item)
{
var parentDiv = document.getElementById('thelist');
var childDiv = document.createElement('li');
var span1 = document.createElement('span');
span1.style.float='left';
span1.innerHTML = "<img src='keypad-contact.png'/>";
var span2 = document.createElement('span');
span2.style.float='right';
span2.innerHTML="<img src='keypad-addcontact.png'/>";
span2.addEventListener('click',function({checkDuplicate(item.number);},false);
childDiv.textContent=item.name;
childDiv.style.color='white';
childDiv.appendChild(span1);
childDiv.appendChild(span2);
parentDiv.appendChild(childDiv);
}
function onSuccess(contacts)
{
var objArray = new Array();
for(var i=0; i<contacts.length;i++) {
var tempObj = new Object();
tempObj['name']=contacts[i].displayName;
tempObj['number']=contacts[i].phoneNumbers[0].value;
objArray.push(tempObj);
}
objArray.sort(
function(a,b){
var nameA = a.name.toLowerCase(),nameB=b.name.toLowerCase();
if(nameA < nameB) return -1;
else if(nameA > nameB) return 1;
return 0;
});
for(var i=0; i<objArray.length;i++) addContact(objArray[i]);
}
function onDeviceReady()
{
var options = new ContactFindOptions();
options.multiple=true;
var field = ["displayName","phoneNumbers"];
navigator.contacts.find(field, onSuccess, function(){alert('NA');}, options);
}
Problem
When I try to add a contact which is already present in window.localStorage, for my first touch on span2, I get one alert. If I try to add again by touching it for the second time, I get two alerts.. and this goes on. The trouble is with the event handler associated with span2. However, I don't know how to over come this situation. How can I ensure that irrespective of how many times I press span2, I get alert only once. How to remove the event handler as soon as it is fired?
Please help.
Fixed:
The issue was not with adding event handlers dynamically. I happen to use iScroll (cubiq) for my project and that caused the trouble. Now I am not receiving multiple alerts. The trick is to declare the globlal scroller variable only once.
var scroller = null;
and then in the function
if(!scroller) scroller = new iScroll('scrollableDiv');
I hope this could be a useful tip for people who are using iScroll and struggling with multiple alerts like me.

Javascript Google Maps Clearing HTML upon map reset function

I am needing to clear a DIV that is created from Google maps function.
There are two HTML DIVs. The DIV I am having trouble with is MarkerCount
<div id="sidebar"></div>
<div id="MarkerCount"></div>
function createMarkerCount(count) {
var div = document.createElement('div');
var html = "Results: " + count + " Facilities";
div.innerHTML = html;
div.style.marginBottom = '5px';
return div;
}
This is created when markers are returned to the Google Map. This is basically performing a count on the amount of records currently displayed on the map. This function works fine.
Here is my function to reset the map and clear the markers and another innerhtml DIV called sidebar:
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
sidebar.innerHTML = "";
map.setCenter(new google.maps.LatLng(36.1611, -116.4775), 6);
}
This function works just fine. Now when I want to clear the MarkerCount,
I tried to add the following line to the function clearLocations()
MarkerCount.innerHTML = "";
However when the page first loads, and you perform a search, the clearLocations() function is called before the search is started, because there is not currently an innerhtml created for the CreateMarker function. this throws back an error which states that CreateMarker is NULL as there is nothing there.
So the skinny is, sidebar.innerhtml gets cleared just fine, but when I add the line of code to clear the CreateMarker.innerhtml DIV, I receive an error. Not sure why this might be happening....
EDIT -- Function To Show How CountMarker Gets Count
var markercountEntry = createMarkerCount(markerNodes.length);
MarkerCount.appendChild(markercountEntry);
It sounds like you are having problems with setting an innerHTML on an element that is not defined yet, in your clearLocations() function. I suggest you just handle the case where CreateMarker or MarkerCount is not defined yet.
Something like:
function clearLocations() {
if(CreateMarker && CreateMarker.innerHTML)
CreateMarker.innerHTML = "";
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
sidebar.innerHTML = "";
map.setCenter(new google.maps.LatLng(36.1611, -116.4775), 6);
}

Categories