I want to remove an individual marker from Google map. I am using version 3 API. I know how I can remove all the markers by maintaining a markerArray and setting map null for all.
For removing one by one, I am thinking to make a key value pair combination. So that I give a key and remove the particular marker. I need help over this.
Following is the code, that I use to dram marker:
function geoCodeAddresses(data) {
var markerInfo = {addressKey: '', marker:''};
for (var i = 0; i < data.length; i++) {
myLocation = data[i];
geocoder.geocode({"address":myLocation}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({map:map, position:results[0].geometry.location});
// checkpoint A
alert(myLocation);
/*
markerInfo.addressKey = myLocation;
markerInfo.marker = marker;*/
//mArray.push(markerInfo);
}
});
}
}
I will search for addresskey and remove the marker from mArray. But I get last value every time in geocode callback method. And one object got pushed every time. the var myLocation always give me the address of the last index of my array. If I alert it at check point A.
My approach is right?
Your problem is this line:
mArray.push(markerInfo);
That doesn't push the values of markerInfo into your array. It pushes a reference to markerInfo into your array. Now, on your next iteration of the loop, when you change the value of markerInfo, it changes the value pointed at by the references in the array too. So your array ends up having elements that all have the same value.
Try this instead:
mArray.push({addressKey:myLocation,marker:marker});
If that doesn't work, then this:
mArray.push({addressKey:data[i],marker:marker});
Related
I need to update a collection in values like this :
{
"email" : "x#gmail.com",
"fullName" : "Mehr",
"locations" : ["sss","dsds","adsdsd"]
}
Locations needs to be an array. in firebase how can I do that ... and also it should check duplicated.
I did like this :
const locations=[]
locations.push(id)
firebase.database().ref(`/users/ + ${userId}`).push({ locations })
Since you need to check for duplicates, you'll need to first read the value of the array, and then update it. In the Firebase Realtime Database that combination can is done through a transaction. You can run the transaction on the locations node itself here:
var locationsRef = firebase.database().ref(`/users/${userId}/locations`);
var newLocation = "xyz";
locationsRef.transaction(function(locations) {
if (locations) {
if (locations.indexOf(newLocation) === -1) {
locations.push(newLocation);
}
}
return locations;
});
As you can see, this loads the locations, ensures the new location is present once, and then writes it back to the database.
Note that Firebase recommends using arrays for set-like data structures such as this. Consider using the more direct mapping of a mathematical set to JavaScript:
"locations" : {
"sss": true,
"dsds": true,
"adsdsd": true
}
One advantage of this structure is that adding a new value is an idempotent operation. Say that we have a location "sss". We add that to the location with:
locations["sss"] = true;
Now there are two options:
"sss" was not yet in the node, in which case this operation adds it.
"sss" was already in the node, in which case this operation does nothing.
For more on this, see best practices for arrays in Firebase.
you can simply push the items in a loop:
if(locations.length > 0) {
var ref = firebase.database().ref(`/users/ + ${userId}`).child('locations');
for(i=0; i < locations.length; i++) {
ref.push(locations[i]);
}
}
this also creates unique keys for the items, instead of a numerical index (which tends to change).
You can use update rather than push method. It would much easier for you. Try it like below
var locationsObj={};
if(locations.length > 0) {
for(i=0; i < locations.length; i++) {
var key= firebase.database().ref(`/users/ + ${userId}`).child('locations').push().key;
locationsObj[`/users/ + ${userId}` +'/locations/' + key] =locations[i];
}
firebase.database().ref().update(locationsObj).then(function(){// which return the promise.
console.log("successfully updated");
})
}
Note : update method is used to update multiple paths at a same time. which will be helpful in this case, but if you use push in the loop then you have to wait for the all the push to return the promises. In the update method it will take care of the all promises and returns at once. Either you get success or error.
Hoping someone here can help me, I have the below code:
function getSSData(){
var values = SpreadsheetApp.openById('1iKO7j_ETu_x1iJf7y_ih76sDTBS21JULid_5pNIit8w').getSheets()[0].getDataRange().getValues();
var ssData = [];
// app.datasources.P11d.unload(function(){});
console.log('Made it to Line 5');
for (var i = 0; i<values.length; i++){
var newRecord = app.models.P11d.newRecord();
// add all fields to the new record
console.log('Made it to Line 9');
newRecord.MODEL_FIELD = values[i][0];
ssData.push(newRecord);
// console.log(newRecord.MODEL_FIELD);
}
console.log('Finished');
// return the array of the model.newRecord objects that would be consumed by the Model query.
return ssData;
}
I have taken this from another post on here, however I can't seem to understand what is happening around the MODEL_FIELD section. Do I need to specify each column title individually or will this just know what to do?
Thank you in advance and I'm sorry if the question seems simple, I'm still very new at this and trying to pick it up as I go along.
values is a 2d array of all of the data in your sheet.
Effectively, the code iterates over all of the rows retrieved from the sheet. For each row a new record is created and the value in the first column of each row is assigned to the field MODEL_FIELD in the new record.
Each new record is pushed into another array which is returned to the caller to be saved with app.saveRecords();
Given this code:
var Container = CRM.GetBlock("Container");
var CustomCommunicationDetailBox = CRM.GetBlock("CustomCommunicationDetailBox");
Container.AddBlock(CustomCommunicationDetailBox);
if(!Defined(Request.Form)){
CRM.Mode=Edit;
}else{
CRM.Mode=Save;
}
CRM.AddContent(Container.Execute());
var sHTML=CRM.GetPageNoFrameset();
Response.Write(sHTML);
Im calling this .asp page with this parameters but does not seems to work
popupscreeens.asp?SID=33185868154102&Key0=1&Key1=68&Key2=82&J=syncromurano%2Ftabs%2FCompany%2FCalendarioCitas%2Fcalendariocitas.asp&T=Company&Capt=Calendario%2Bcitas&CLk=T&PopupWin=Y&Key6=1443Act=512
Note the Key6=Comm_Id and Act=512??? which i believe it is when editing?
How can i achieve to fill the screen's field with entity dada?
In this case it is a communication entity
In order to populate a custom screen with data, you need to pass the data to the screen.
First, you need to get the Id value. In this case, we're getting it from the URL:
var CommId = Request.QueryString("Key6") + '';
We're going to put a few other checks in though. These are mainly to handle scenarios that have come up in different versions or from different user actions.
// check we have a value and get the Id from context if we don't
if(CommId == 'undefined'){
CommId = CRM.GetContextInfo("Communication","comm_communicationid");
}
// if CommId is still undefined, set it to zero to check later
// otherwise, make sure the URL only contains one CommId
if(CommId == 'undefined'){
CommId = 0;
} else if(CommId.indexOf(",") > -1){
CommId = CommId.substr(0,CommId.indexOf(","));
}
Certain user actions can make the URL hold multiple Ids in the same attribute. In these cases, those Ids are separated by commas. So, if the Id is not defined, we check if there is a comma in it. If there is, we take the 1st Id.
After we have the Id, we need to load the record. At this point, you should have already checked you have a valid id (E.g. not zero) and put some error handling in. In some pages you may want to display an error, in others you may want to create a new, blank record. This gets the record:
var CommRecord = CRM.FindRecord("communication","comm_communicationid = " + CommId);
After that, you need to apply the record to the screen. Using your example above:
CustomCommunicationDetailBox.ArgObj = CommRecord;
Adding all that to your script, you get:
var CommId = Request.QueryString("Key6") + '';
// check we have a value and get the Id from context if we don't
if(CommId == 'undefined'){
CommId = CRM.GetContextInfo("Communication","comm_communicationid");
}
// if CommId is still undefined, set it to zero to check later
// otherwise, make sure the URL only contains one CommId
if(CommId == 'undefined'){
CommId = 0;
} else if(CommId.indexOf(",") > -1){
CommId = CommId.substr(0,CommId.indexOf(","));
}
// add some error checking here
// get the communication record
var CommRecord = CRM.FindRecord("communication","comm_communicationid = " + CommId);
// get the container and the detail box
var Container = CRM.GetBlock("Container");
var CustomCommunicationDetailBox = CRM.GetBlock("CustomCommunicationDetailBox");
// apply the communication record to the detail box
CustomCommunicationDetailBox.ArgObj = CommRecord;
// add the box to the container
Container.AddBlock(CustomCommunicationDetailBox);
// set the moder
if(!Defined(Request.Form)){
CRM.Mode=Edit;
} else {
CRM.Mode=Save;
}
// output
CRM.AddContent(Container.Execute());
var sHTML=CRM.GetPageNoFrameset();
Response.Write(sHTML);
However, we would advise putting in more error/exception handling. If the user is saving the record, you will also need to add a redirect in after the page is written.
Six Ticks Support
I use Places library to autocomplete address input. Search is limited to only one city, and I get output like this:
"Rossiya, Moskva, Leninskiy prospekt 28"
How to hide "Rossiya, Moskva"? ...
My query:
function() {
// Search bounds
var p1 = new google.maps.LatLng(54.686534, 35.463867);
var p2 = new google.maps.LatLng(56.926993, 39.506836);
self.options = {
bounds : new google.maps.LatLngBounds(p1, p2),
componentRestrictions: {country: 'ru'},
};
var elements = document.querySelectorAll('.address');
for ( var i = 0; i < elements.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(elements[i],
self.options);
}
You can but you have to replace the value of the input field in two places.
Example:
var autocomplete = new google.maps.places.Autocomplete(input, placesOptions);
var input = document.getElementById('searchTextField');
inside the 'place_changed' event you need to do the following:
placeResult = autocomplete.getPlace();
//This will get only the address
input.value = placeResult.name;
This will change the value in the searchtextfield to the street address.
The second place is a bit tricky:
input.addEventListener('blur', function(){
// timeoutfunction allows to force the autocomplete field to only display the street name.
if(placeResult){ setTimeout(function(){ input.value = placeResult.name; }, 1); } });
The reason why we have to do this is because if you only add the event listener for blur, google places will populate the input field with the full address, so you have to 'wait' for google to update and then force your change by waiting some miliseconds.
Try it without the setTimeout function and you will see what I mean.
EDIT
You can't. I had it the other way around, that you were just looking for a city. There is no way to only print out the street name (I'm assuming that's a street name) from the address component.
OPPOSITE OF WHAT WAS ASKED
From the docs:
the (cities) type collection instructs the Place service to return results that match either locality or administrative_area3.
var input = document.getElementById('searchTextField');
var options = {
bounds: defaultBounds,
types: ['(cities)']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
in result u have hash and from it u can get part what u want:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
now from "place" u can get it
place.geometry.location.lat()
and for address
place.address_components[0] or place.address_components[1] ...
depends on what u want to get
I had a very similar problem which indeed was solvable. This in an Angular 2 project but it should be applicable elsewhere as well. I filter my results for establishments, and wanted to show only the name and hide the address part of the result. This did the trick for me, a function executing once you select a suggestion:
getAddress(place: Object) {
this.zone.run(() => {
this.establishment = place['name'];
});
where zone is an NgZone component injected in the constructor and this.establishment is the variable tied to [(NgModel)] in the input field.
Inside place_changed set a timeout function:
var streetString = place.address_components[0] or place.address_components[1];
window.setTimeout(function() {
$('input').val(streetString);
}, 200);
This solution worked for me.
I can't make my multiple-check-box filtering system to work. I'll explain the problem, the research I've done here on stackoverflow, and why I still need help after that.
My problem is that my check boxes can't bring back the markers when I gradually unselect them. These said filters work well when I click them, because they incrementally fade away the markers associated with them. However, after just unselecting a couple of these checkboxes, all the markers are back on screen, and the last boxes don't do anything when they are finally unclicked.
This is the temporary URL of the project: http://www.lcc.gatech.edu/~amartell6/php/main12.php
This is the code where I'm getting stuck:
//this getJson function exists within an init funciton where a map
//has already been called
$.getJSON(theUrl,function(result){
$.each(result, function(i, item){
//get Longitude
var latCoord = item.coordinate;
var parenthCoord = latCoord.indexOf(",");
var partiaLat = latCoord.substr(1,parenthCoord-1);
var lat = parseFloat(partiaLat);
//alert(lat);
//get Latitude
var lngCoord = item.coordinate;
var commaCoord = lngCoord.indexOf(",");
var partiaLng = lngCoord.substr(commaCoord+1);
var lng = parseFloat(partiaLng);
//alert(lng);
// display ALL the story markers
var storyMarker;
storyMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),// ----- > whithin the mutidimentional array,
map: map
});
//display the stories by clicking on the markers
google.maps.event.addListener(storyMarker, 'click', function() {
var from = "From ";
if(item.end_date != ""){
item.end_date = " to " + item.end_date;
}
else{
from = "";
}
$('#output').html(
'<p><span class="selected">Type of Entry: </span>' +
item.entry_type + ' <br/><br/>'+
'<span class="selected">Title: </span>'+ item.entry_title + '<br/><br/>' +
'<span class="selected">Date(s):</span><br/>'+ from +item.start_date+
//' to '+item.end_date+'<br/><br/>'+
item.end_date+'<br/><br/>'+
'<span class="selected">Content:</span><br/><br/> '+ item.entry
+'</p>'
);
});// end of story displays
//call filters from filter funciton
filter('#evacuation-filter',item.evacuation,"Yes");
filter('#evacuation-order-filter',item.evacuation_order,"Yes");
filter('#w-nearby-filter',item.w_nearby,"Yes");
filter('#hurricane-reached-filter',item.hurricane_reached,"Yes");
filter('#outdoors-filter',item.in_out_doors,"Outdoors Most of the Time");
filter('#indoors-filter',item.in_out_doors,"Indoors Most of the Time");
filter('#food-filter',item.food,"Yes");
filter('#windows-filter',item.windows,"Yes");
filter('#power-filter',item.power,"Yes");
filter('#wounded-filter',item.wounded,"Yes");
filter('#looting-filter',item.looting,"Yes");
filter('#blackouts-filter',item.blackouts,"Yes");
filter('#trees-filter',item.trees,"Yes");
filter('#powerlines-filter',item.powerlines,"Yes");
filter('#light-filter',item.light,"Yes");
filter('#sidewalks-filter',item.sidewalks,"Yes");
filter('#buildings-filter',item.buildings,"Yes");
filter('#flooding-filter',item.flooding,"Yes");
//FILTER FUNCTION
//first parameter is the checkbox id, the second is the filter criteria
//(the filter function has to be called within the $.each loop to be within scope)
var otherFilter = false;
function filter(id, criterion1, value){
var activeFilters = [];
$(id).change(function() {
//evalute if the checkbox has been "checked" or "unchecked"
var checkBoxVal = $(id).attr("checked");
//if it's been checked:
if(checkBoxVal=="checked"){
//1 - Get markers that don't talk about the filter
if(criterion1!=value && storyMarker.getVisible()==true){
//2 - fade them away, and leave only those meet the criteria
storyMarker.setVisible(false);
otherFilter = true;
activeFilters.push(criterion1);
//document.getElementById("text3").innerHTML=activeFilters+"<br/>";
//alert(activeFilters.push(criterion1) +","+criterion1.length);
}
}
//if it's been unchecked:
else if(checkBoxVal==undefined){
//1 - Get markers that don't talk about the filter
if(criterion1!=value && storyMarker.getVisible()==false){
//2 - Show them again
storyMarker.setVisible(true);
otherFilter = false;
activeFilters.pop(criterion1);
//alert(activeFilters.pop(criterion1) +","+criterion1.length);
} //end of if to cancel filter and bring markers and stories back
}
}); // end of change event
} // end of filter function
//var otherDropDown = false;
filter2("#media-filter",item.media);
filter2("#authorities-filter",item.authorities);
//---------------
function filter2(id2,criterion2){
$(id2).change(function() {
//get the value of the drowpdown menu based on its id
var dropDownVal = $(id2).attr("value");
var all="All";
//if the value isn't "All", other filters have not been applied, and marker is on screen
if(dropDownVal!=all && otherFilter==false){
//1 - check if the marker doesn't comply with filter
if(criterion2!=dropDownVal){
//2 - fade them away if not, and leave only those meet the criteria
storyMarker.setVisible(false);
//3 - If the marker does comply with it
}else if(criterion2==dropDownVal){
//4 - keep it there
storyMarker.setVisible(true);
}//end of filter applier
//else if if the value IS "All", filters have not been applied, and marker is faded
}else if(dropDownVal==all && otherFilter==false){
//select all the possible values for the cirterion
if(criterion2!=undefined){
//and show all those markers
storyMarker.setVisible(true);
}
}
});
} //end of function filter2
}); // end of $.each
}); // end of $.getJSON
I found one related blog post. This one suggests adding a category to the markers. However, when I do that, the filters keep working the same way. I think this happens because each filter is programmed to hide every single marker that meets their selecting criteria, but each marker has more than one property they can be filtered with.
Do you know if there is a way to make the script detect how many filters point towards the same marker, and only show it back if no filters are pointing at it? This is my guess on how to solve it, even though I don't know how to make it happen in code.
Finally, if you know of alternate ways to make the filters work, let me know.
I created an application with similar logic several years ago http://www.ioos.gov/catalog/ But it was for GMap 2.0 but I think the logic would be the same.
My approach was to extend the Google maps Marker object (already bloated) with features I wanted to filter them on.
These would be all the properties you're storing in your 'click' listener and perhaps more: e.g. item.title, item_start_date, etc. whatever you eventually want to filter your marker by.
var all_markers = [];
storyMarker.end_date = item.end_date;
storMarker.title = item.title;
...
all_markers.push(storyMarker);
Then when you want to filter loop thru all the markers, check the marker value against the filter condition and setVisible(true) or false as need.
Erik already provided a solution to my problem. However, I think the community may benefit from reading other options, and I want to share the solution I came up with. Even if it may not be the most effective, it works.
In the code I just mentioned, I declared all the storyMarkers at once when the map initializes:
// display ALL the story markers
var storyMarker;
storyMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),// ----- > whithin the mutidimentional array,
map: map
});
Now, I added a new argument to the markers, but instead of creating a variable as in the example I had found in other post, this argument was an empty array:
storyMarker.pointer = [];
The previous filter function had three levels. The first level detected a change in the check box. The second one verified whether the check box had been checked or unchecked. The third level ran the filter on e-v-e-r-y marker, either to show it or hide it.
This is where my solution began. Within the most inner if statement of the filter function, I added a discretionary element within the pointer array:
storyMarker.pointer.push("element");
Right after this, I nested a new if statement to check if the array is not empty. If it indeed isn't empty, the program hides the marker that this array belongs to.
The program inverses the logic when a box is unchecked. It calls-off the filter, subtracts one element from the array associated with that marker, and then checks if there are other markers associated with it. The system now only shows up markers whose arrays are empty.
//alert(storyMarker.pointer);
function filter(id,criterion,value){
$(id).change(function() {
var checkBoxVal = $(id).attr("checked");
if(checkBoxVal=="checked"){
if(criterion!=value){
storyMarker.pointer.push("element");
//alert("array length: "+storyMarker.pointer.length);
if(storyMarker.pointer.length>0){
storyMarker.setVisible(false);
}
}
}
else if(checkBoxVal!="checked"){
if(criterion!=value){
storyMarker.pointer.pop("element");
//alert("array length: "+storyMarker.pointer.length);
if(storyMarker.pointer.length<=0){
storyMarker.setVisible(true);
}
}
}
});
}
In summary, the script is still clicking a marker more multiple times if the user clicks on more than one marker. The system can now recognize how many times is one marker pointed out, and only show the one that has no pointers at all.