Check/uncheck element through link inside Google Earth - google-earth

So I have a folder with 2 placemarks in it. One of them is hidden on load while the other is visible. I'd like to have a link in the description of the visible one to hide/show the hidden one. Is there a way to do this?

If you are using the Google Earth plugin, this is one way of doing it.
First assign each placemark an 'id' - so in the KML file you need to edit the code that says
<Placemark>
<name>Placemark 1</name>
to
<Placemark id="placemark1">
<name>Placemark 1</name>
and the same for Placemark #2
then you have a javascript function like the one below, which is executed by adding a button through the balloon description (see this example page for how to do that)
function togglePlacemarks() {
var pm1 = ge.getElementById('placemark1');
var pm1 = ge.getElementById('placemark1');
if (pm1.getVisibility() == true) {
pm1.setVisibility(false);
pm2.setVisibility(true);
} else {
pm1.setVisibility(true);
pm2.setVisibility(false);
}
}
In the example code to execute JS from a balloon, you would change the following line
balloon.setContentString(
'Alert!');
to
balloon.setContentString(
'Toggle Visibility');
Finally, if you only wish to have a simple (ie only 2 placemarks), then perhaps you should use the example code to create your placemarks instead of creating and loading a custom KML file. In which case, when you create the placemarks (through this line of code)
placemark = ge.createPlacemark('');
You would do this
placemark1 = ge.createPlacemark('placemark1');
...etc
and also
placemark2 = ge.createPlacemark('placemark2');
... etc
placemark2.setVisibility(false);

Related

leafeltjs (mapbox) z-index ordering not working

Another developer created our original map but I'm tasked with making some changes. One of these is making sure the activated marker is brought to the front when clicked on (where it is partially overlapped by other markers).
The developers have used mapbox 2.2.2.
I have looked at leafletjs's docs, have followed some instructions on other posted solutions (e.g. solution one and solution two). Neither of these makes any difference.
Examining the marker in Chrome's console I can see the value of options.zIndexOffset is being set (10000 in my test case). I've even set _zIndex to an artificially high value and can see that reflected in the marker's data structure. But visually nothing is changing.
This is how the map is set up initially. All features are from a single geojson feed:
L.mapbox.accessToken = '<access token here>';
var map = L.mapbox.map('map', 'map.id', {
}).setView([37.8, -96], 3);
var jsonFeed, jsonFeedURL;
var featureLayer = L.mapbox.featureLayer()
.addTo(map)
.setFilter(function (f) {
return false;
});
$.getJSON(jsonFeedURL, function (json) {
jsonFeed = json;
jsonFeedOld = json;
// Load all the map features from our json file
featureLayer.setGeoJSON(jsonFeed);
}).done(function(e) {
// Once the json feed has loaded via AJAX, check to see if
// we should show a default view
mapControl.activateInitialItem();
});
Below is a snippet of how I had tried setting values to change the z-index. When a visual marker on the featureLayer is clicked, 'activateMarker' is called:
featureLayer.on('click', function (e) {
mapControl.activateMarker(e);
});
The GEOjson feed has urls for the icons to show, and the active marker icon is switched to an alternative version (which is also larger). When the active feature is a single Point I've tried to set values for the marker (lines commented out, some of the various things I've tried!)
activateMarker: function (e) {
var marker = e.layer;
var feature = e.layer.feature;
this.resetMarkers();
if (feature.properties.hasOwnProperty('icon')) {
feature.properties.icon['oldIcon'] = feature.properties.icon['iconUrl'];
feature.properties.icon['iconUrl'] = feature.properties.icon['iconActive'];
feature.properties.icon['oldIconSize'] = feature.properties.icon['iconSize'];
feature.properties.icon['iconSize'] = feature.properties.icon['iconSizeActive'];
}
if (feature.geometry.type == 'Point') {
marker.setZIndexOffset(10001);
marker.addTo(featureLayer);
}
//featureLayer.setGeoJSON(jsonFeed);
}
Any advice would be greatly appreciated! I'm at the point where I don't know what else to try (and that's saying something).
What probably happens is that you just flush your markers with the last call to .setGeoJSON():
If the layer already has features, they are replaced with the new features.
You correctly adjust the GeoJSON data related to your icon, so that when re-created, your featureLayer can use the new values to show a new icon (depending on how you configured featureLayer).
But anything you changed directly on the marker is lost, as the marker is removed and replaced by a new one, re-built from the GeoJSON data.
The "cleanest" way would probably be to avoid re-creating all features at every click.
Another way could be to also change something else in your GeoJSON data that tells featureLayer to build your new marker (through the pointToLayer option) with a different zIndexOffset option.

Why doesn't marker.dragging.disable() work?

The following code receives an error on the lines for enabling and disabling the marker dragging ("Unable to get property 'disable' of undefined or null reference"). The markers show up on the map just fine and are draggable as the creation line indicates. Placing an alert in place of the enable line produces a proper object so I believe the marker is defined. Is there something I need to do to enable the IHandler interface? Or am I missing something else?
var marker = L.marker(L.latLng(lat,lon), {icon:myIcon, draggable:'true'})
.bindLabel(name, {noHide: true,direction: 'right'});
marker._myId = name;
if (mode === 0) {
marker.dragging.enable();
} else {
marker.dragging.disable();
}
I had a similar problem today (perhaps the same one) it was due to a bug in leaflet (see leaflet issue #2578) where changing the icon of a marker invalidates any drag handling set on that marker. This makes any calls to marker.dragging.disable() fail.
The fix hasn't made it into leaflets master at time of writing. A workaround is to change the icon after updating the draggable status if possible.
marker.dragging.disable();
marker.setIcon(marker_icon);
Use the following code to make an object draggable. Set elementToDrag to the object you wish to make draggable, which is in your case: "marker"
var draggable = new L.Draggable(elementToDrag);
draggable.enable();
To disable dragging, use the following code:
draggable.disable()
A class for making DOM elements draggable (including touch support).
Used internally for map and marker dragging. Only works for elements
that were positioned with DomUtil#setPosition
leaflet: Draggable
If you wish to only disable the drag option of a marker, then you can use the following code (where "marker" is the name of your marker object):
marker.dragging.disable();
marker.dragging.enable();
I haven't found an answer but my workaround was this:
var temp;
if (mode === 0) {
temp = true;
} else {
temp = false;
}
var marker = L.marker(L.latLng(lat,lon), {icon:myIcon, draggable:temp})
.bindLabel(name, {noHide: true,direction: 'right'});
marker._myId = name;
Fortunately I change my icon when it is draggable.

Having trouble attaching event listener to a kml layer's polygon

Using Google Earth I have a loaded kml layer that displays polygons of every county in the US. On click a balloon pop's up with some relevant info about the state (name, which state, area, etc) When a user clicks the polygon I want the information to also pop up on a DIV element somewhere else.
This is my code so far.
var ge;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
ge.getNavigationControl().setStreetViewEnabled(true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
//here is where im loading the kml file
google.earth.fetchKml(ge, href, function (kmlObject) {
if (kmlObject) {
// show it on Earth
ge.getFeatures().appendChild(kmlObject);
} else {
setTimeout(function () {
alert('Bad or null KML.');
}, 0);
}
});
function recordEvent(event) {
alert("click");
}
// Listen to the mousemove event on the globe.
google.earth.addEventListener(ge.getGlobe(), 'click', recordEvent);
}
function failureCB(errorCode) {}
google.setOnLoadCallback(init);
My problem is that when I change ge.getGlobe() to kmlObject or ge.getFeatures() it doesn't work.
My first question is what should I change ge.getGlobe() to to be able to get a click listener when a user clicks on a kml layer's polygon?
After that I was planning on using getDescription() or getBalloonHtml() to get the polygons balloons information. Am I even on the right track?
...what should I change ge.getGlobe() to...
You don't need to change the event object from GEGlobe. Indeed it is the best option as you can use it to capture all the events and then check the target object in the handler. This means you only have to set up a single event listener in the API.
The other option would be to somehow parse the KML and attach specific event handlers to specific objects. This means you have to create an event listener for each object.
Am I even on the right track?
So, yes you are on the right track. I would keep the generic GEGlobe event listener but extend your recordEvent method to check for the types of KML object you are interested in. You don't show your KML so it is hard to know how you have structured it (are your <Polygon>s nested in <Placemarks> or ` elements for example).
In the simple case if your Polygons are in Placemarks then you could just do the following. Essentially listening for clicks on all objects, then filtering for all Placmark's (either created via the API or loaded in via KML).
function recordEvent(event) {
var target = event.getTarget();
var type = target.getType();
if(type == "KmlPolygon") {
} else if(type == "KmlPlacemark") {
// get the data you want from the target.
var description = target.getDescription();
var balloon = target.getBalloonHtml();
} else if(type == "KmlLineString") {
//etc...
}
};
google.earth.addEventListener(ge.getGlobe(), 'click', recordEvent);
If you wanted to go for the other option you would iterate over the KML Dom once it has loaded and then add events to specific objects. You can do this using something like kmldomwalk.js. Although I wouldn't really recommend this approach here as you will create a large number of event listeners in the api (one for each Placemark in this case). The up side is that the events are attached to each specific object from the kml file, so if you have other Plaemarks, etc, that shouldn't have the same 'click' behaviour then it can be useful.
function placeMarkClick(event) {
var target = event.getTarget();
// get the data you want from the target.
var description = target.getDescription();
var balloon = target.getBalloonHtml();
}
google.earth.fetchKml(ge, href, function (kml) {
if (kml) {
parseKml(kml);
} else {
setTimeout(function () {
alert('Bad or null KML.');
}, 0);
}
});
function parseKml(kml) {
ge.getFeatures().appendChild(kml);
walkKmlDom(kml, function () {
var type = this.getType();
if (type == 'KmlPlacemark') {
// add event listener to `this`
google.earth.addEventListener(this, 'click', placeMarkClick);
}
});
};
Long time since i have worked with this.. but i can try to help you or to give you some tracks...
About your question on "google.earth.addEventListener(ge.getGlobe(), 'click', recordEvent);"
ge.getGlobe can not be replaced with ge.getFeatures() : if you look in the documentation ( https://developers.google.com/earth/documentation/reference/interface_g_e_feature_container-members) for GEFeatureContainer ( which is the output type of getFeatures() , the click Event is not defined!
ge.getGlobe replaced with kmlObject: waht is kmlObject here??
About using getDescription, can you have a look on the getTarget, getCurrentTarget ...
(https://developers.google.com/earth/documentation/reference/interface_kml_event)
As I told you, i haven't work with this since a long time.. so I'm not sure this can help you but at least, it's a first track on which you can look!
Please keep me informed! :-)

How to have an Apps Script Gadget display results directly in the UI

On my Google Site I've inserted an Apps Script Gadget (by pasting the URL of an Apps Script that I published as a service). This Apps Script allows the user to enter a value (their 'Blow Number') and view the corresponding data (based on API calls to my Google Fusion tables).
Right now, the script returns 3 hyperlinks:
Click here for a table of Blow Number 1
Click here for a chart of Blow Number 1
Click here for a map of Blow Number 1
This is because my script function getblowdetails has 3 app.createAnchor variables. Instead of having the script return 3 hyperlinks (that the user has to click on and view the resulting URL in a new window), I would like for the script to automatically invoke the 3 URLs and display the table, chart, and map in panels on the same page.
So the user would enter their Blow Number and press enter. They would then view the table, chart, and map directly below the text box on the same web page.
Please see the Code that I've included below and advise...Thanks for the help- I'm an apps-script novice so a thorough and understand-able response is greatly appreciated!
Code
Note: I've removed the URLs from the createAnchor variables because I'm only allowed to include 2 links in the post, but you can see them by going to www.OnSiteBAC.com/ViewMyBlows and entering Blow Number = 1...then click on the hyperlinks.
function doGet() {
var app = UiApp.createApplication();
// Create input boxes, buttons, labels, and links
var textBoxA = app.createTextBox().setId('textBoxA').setName('textBoxA').setFocus(true);
var buttonA = app.createButton('Get Blow Details').setEnabled(false);
var label = app.createLabel('Please enter your Blow Number here');
var link = app.createAnchor('where can I find my Blow Number?', 'http://www.onsitebac.com');
// Create a handler to call the getblowdetails function.
// A validation is added to this handler so that it will only invoke 'getblowdetails' if textBoxA contains a number
var handler = app.createServerClickHandler('getblowdetails').validateNumber(textBoxA).addCallbackElement(textBoxA);
// Create a handler to enable the button if all input is legal
var onValidInput = app.createClientHandler().validateNumber(textBoxA).forTargets(buttonA).setEnabled(true).forTargets(label, link).setVisible(false);
// Create a handler to mark invalid input in textBoxA and disable the button
var onInvalidInput1 = app.createClientHandler().validateNotNumber(textBoxA).forTargets(buttonA).setEnabled(false).forTargets(textBoxA).setStyleAttribute("color", "red").forTargets(label, link).setVisible(true);
// Create a handler to mark the input in textBoxA as valid
var onValidInput1 = app.createClientHandler().validateNumber(textBoxA).forTargets(textBoxA).setStyleAttribute("color", "black");
// only fire ServerHandler for onKeyUp if it passes validation
var textBoxHandler = app.createServerHandler('textBoxHandlerFunction');
// Add all the handlers to be called when the user types in the text boxes
textBoxHandler.addCallbackElement(textBoxA);
textBoxA.addKeyUpHandler(onInvalidInput1);
textBoxA.addKeyUpHandler(onValidInput1);
textBoxA.addKeyUpHandler(onValidInput);
textBoxA.addKeyUpHandler(textBoxHandler);
buttonA.addClickHandler(handler);
app.add(textBoxA);
app.add(buttonA);
app.add(label);
app.add(link);
return app;
}
function textBoxHandlerFunction(e) {
var app = UiApp.getActiveApplication();
if (e.parameter.keyCode == 13)
{
app = getblowdetails(e);
}
return app;
}
function getblowdetails(e) {
var app = UiApp.getActiveApplication();
var panel2 = app.createVerticalPanel();
var link2 = app.createAnchor ().setStyleAttribute("color", "green");
var panel3 = app.createVerticalPanel();
var link3 = app.createAnchor ();
var panel4 = app.createVerticalPanel();
var link4 = app.createAnchor ();
panel3.add(link3);
app.add(panel3);
panel4.add(link4);
app.add(panel4);
return app;
}
I don't think you'll be able to actually download the result and show it. So, there's no easy solution.
But you can build that table and chart on Apps Script easily (assuming you can already fetch the info from tables using its API).
The last issue is the map. On Apps Script you can only create static maps, meaning, an image. You can add custom markers and polygons, set the zoom, etc. But in the end it's a photo. The user will not be able to drag it around or use the map as an embedded google map as one would expect.

How to prevent overlapping pushpins at the same geolocation with Bing Maps?

If you have 2 pushpins on 'London' at the same geolocation, is there anything in the API to move them apart so they are both visible?
I can only find documentation on their old map points API which had PreventIconCollisions, this is what I want but can't see any reference to this in the new API.
I am using the JavaScript API.
So if I understand correctly, you have similar information on the same location, it this correct?
In order to display both information, you will have two options:
Merge information in the textbox using an appropriate way to present the information inside this ui element (using your own tabbed infobox for example)
Decluster the point manually when you're at a certain level of zoom
There is no default property to set this and it would really messy to do this on many pushpins, but in the main idea, you would have to: detect viewchangeend event, if you're at a certain level of zoom (or higher zoom level) then you're declustering them (I call it decluter nearby pushpins).
// Bind pushpin mouseover.
Microsoft.Maps.Events.addHandler(pin, 'mouseover', function (e) {
var currentPin = e.target;
currentPin.setOptions({ visible: false });
var currentLocation = currentPin.getLocation().clone();
var currentPoint = bmGlobals.geo.map.tryLocationToPixel(currentLocation);
if (currentPin.associatedCluster.length == 2) {
// Display the first pushpin
var pinA = createPin(currentPin.associatedCluster[0]);
var locA = bmGlobals.geo.map.tryPixelToLocation(new Microsoft.Maps.Point(currentPoint.x - pinA.getWidth(), currentPoint.y));
pinA.setLocation(locA);
bmGlobals.geo.layerClusteredPin.push(pinA);
// Display the second pushpin
var pinB = createPin(currentPin.associatedCluster[1]);
var locB = bmGlobals.geo.map.tryPixelToLocation(new Microsoft.Maps.Point(currentPoint.x + pinB.getWidth(), currentPoint.y));
pinB.setLocation(locB);
bmGlobals.geo.layerClusteredPin.push(pinB);
}
});
I will try to write a bing maps module about this, but in the fact, you'll have to get your clustered pushpins (or your own pushpin that has two associated data object) and then you will have to set their position based on the rendering on the client side.
I know this question is really old, but if someone is looking for something similar (clustering the pins) here is a good start: http://rtsinani.github.io/PinClusterer/