Google Earth API doesn't create place mark I want - javascript

I'm making an ASP.net app to show some features on Google Earth.
After reading "Google's Developer Guide" now i'm using this javascript code:
<script type="text/javascript" src="http://www.google.com/jsapi?hl=en&key=MyAPIKey"></script>
<script type="text/javascript">
var ge;
google.load("earth", "1", {"other_params": "sensor=true_or_false"});
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
}
function failureCB(errorCode) {
}
function generator() {
// Create the placemark.
var placemark = ge.createPlacemark('');
placemark.setName("placemark");
// Set the placemark's location.
var point = ge.createPoint('');
point.setLatitude(12.345);
point.setLongitude(54.321);
placemark.setGeometry(point);
// Add the placemark to Earth.
ge.getFeatures().appendChild(placemark);
alert('OK!');
}
google.setOnLoadCallback(init);
</script>
Then have a code like this in c# to run javascript:
b.ID = "btnSomeButton";
b.Text = "Click to generate PlaceMark!";
b.Attributes.Add("onclick", "return generator();");
My page displays the Google Earth but when I click on the button it doesn't create place mark.Where I am wrong?

I dont know what mistake in your program. It may be created successfully. I think you are searching somewhere. After placemark creation try to change your camera view. Try this code after placemark creation:
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.setLatitude(12.345);
lookAt.setLongitude(54.321);
lookAt.setAltitude(1000);
ge.getView().setAbstractView(lookAt);
It may work. I'm not sure.

Related

Google Geochart visualization library not loaded

I have created a Google Geochart widget some time ago with an older Google JS library version. Nowadays Google advised to upgrade to update to the loader api instead of the jsapi. No matter how I load the libraries, for me the visualization library doesn't load properly, hence I get an undefined when trying to instantiate a GeoChart object. Did anybody else encounter this issue as well?
(The JS code is in the form of Dojo widget functions)
update : function(obj, callback){
this._contextObj = obj;
this._resetSubscriptions();
if (this.apiAccessKey && this.apiAccessKey !== "") {
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': this.apiAccessKey
});
google.charts.setOnLoadCallback(this.drawChart(callback));
} else {
var message = " Google Geochart needs an active API key to work!";
console.error(this._logNode + message);
alert(message);
}
},
drawChart : function (callback) {
// Run this as soon as google charts is loaded.
// Create map and its container.
if (!this.geoMap) {
this.geoMap = new google.visualization.GeoChart(this.geoMapContainer);
}
if (this._contextObj){
this._getObjects(this._contextObj.getGuid,callback);
} else {
this._getObjects(null,callback);
}
this._executeCallback(callback);
},
setOnLoadCallback expects a reference to a function --> this.drawChart
not the result of a function --> this.drawChart(callback)
try as follows...
google.charts.setOnLoadCallback(function () {
this.drawChart(callback);
});

Call map.setView for javascript from a function with variables

I am running a django app with tables2. I then set up a field with linkify where i want to zoom to a feature by running a javascript function.
My code in the renderd htm is:
<div id="map" class="leaflet-container-default"></div>
......
<td >Zoom til</td>....
<script type="text/javascript">
function myFunction(lat,long) {
map.setView([lat,long], 15);
}
</script>
Django laflet generatet map script where the map is defined:
<script>
(function () {
function loadmap() {
var djoptions = {"srid": null, "extent": [[-90, -180], [90, 180]], "fitextent": true, "center": [61.2340642364768, 7.10221073722647], "zoom": 12 },
options = {djoptions: djoptions, initfunc: loadmap,
globals: false, callback: window.map_init},
map = L.Map.djangoMap('map', options);
}
var loadevents = ["load"];
if (loadevents.length === 0) loadmap();
else if (window.addEventListener) for (var i=0; i<loadevents.length; i++) window.addEventListener(loadevents[i], loadmap, false);
else if (window.jQuery) jQuery(window).on(loadevents.join(' '), loadmap);
})();
</script>
The map variable shown in the code snippet is internal to the inner scope of the loadmap function. Therefore you can no longer access it later on.
There is probably a way to retrieve it through Django Leaflet API.
Otherwise, if you can have a script executed before Django Leaflet one, you can setup a Leaflet init hook ehich can provide you with the map reference. See Find Leaflet map object after initialisation

Show users coordinates and trigger event

I am using the Geolocation Marker Script from the Google Maps Utilities Library V3 in order to display the position of a user.
What I want to achieve (I am a newbie to the Google Maps API!) is:
have the users current coordinates displayed (e.g. in a simple CSS container somewhere on the page)
connect an event to a marker. I should be triggered when the user is close.
Appreciate your help!
To display coordinates to the user, you would need a reference to a DOM Element. Then it's a simple matter of updating the content.
HTML On the Page
<div id="UserCoordinates">Waiting on GPS Position ...</div>
In Script
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
var UserPosition = this.getPosition();
var DisplayElement = document.getElementById('UserCoordinates');
if(UserPosition === null) {
DisplayElement.innerHTML = 'Waiting on GPS Position...';
} else {
DisplayElement.innerHTML =
'Current Position: ' + UserPosition.toUrlValue();
}
});
This will show the user their current position as it changes. If you are going to continue using a full screen map, you'll probably want to implement the UserCoordinates div as a map control. The API Reference has a good overview and multiple examples on this.
Display an info window when the user is within X meters of a location
This is a little tricky because there are multiple scenarios to handle and you don't want the infowindow opening repeatedly as they move within your radius.
Distance calculation
I see you have a distance function in your code, but I recommend using the one in the Spherical Geometry library of the API. You just have to specifically load the library with your api script tag:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true_or_false">
</script>
Then you need to add to the position_changed event handler:
var IsWithinRadius = false; //assume they start outside of the circle
var RadiusInMeters = 1000; //within 1 km
var LocationOfInterest = map.getCenter();
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
var UserPosition = this.getPosition();
var DisplayElement = document.getElementById('UserCoordinates');
if(UserPosition === null) {
DisplayElement.innerHTML = 'Waiting on GPS Position...';
IsWithinRadius = false; //you don't know where they are
} else {
DisplayElement.innerHTML =
'Current Position: ' + UserPosition.toUrlValue();
var IsCurrentPositionInRadius =
Math.abs(google.maps.geometry.spherical.computeDistanceBetween(
UserPosition, LocationOfInterest)) <= RadiusInMeters;
var JustEnteredRadius = !IsWithinRadius && IsCurrentPositionInRadius;
IsWithinRadius = IsCurrentPositionInRadius;
if(JustEnteredRadius) {
//trigger action here.
alert("Within raidus");
}
}
});

I can't get a kml file loaded with ge plugin to move to the last lat/lon

I have a web page that loads a kml file for viewing using the Google Earth ge plugin. The file loads and displays fine. However, I can get the plugin to move to a lat/lon at the end of the file. The load always leaves the camera at the lat/lon that corresponds to the end point of the kml file.
Here's the code:
var ge;
google.load("earth", "1");
google.load("maps", "2");
function init() {
google.earth.createInstance('map3d', initCallback, failureCallback);
}
function initCallback(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
ge.getOptions().setFlyToSpeed(ge.SPEED_TELEPORT);
var url = 'http://rallyroadie.org/wordpress/ge/vladi_finish.kml';
google.earth.fetchKml(ge, url, finished);
}
function finished(object) {
if (!object) {
setTimeout(function() {
alert('Bad or null KML.');
}, 0);
return;
}
ge.getFeatures().appendChild(object);
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
// Set new latitude and longitude values.
lookAt.setLatitude(43.023157);
lookAt.setLongitude(131.853040);
// Update the view in Google Earth.
ge.getView().setAbstractView(lookAt);
}
function failureCallback(errorCode) {
}
google.setOnLoadCallback(init);
You can see the page at http://rallyroadie.org/wordpress/ge/vladi.html
TIA,
Paul
Are you wanting to know how to set the initial view? If so:
You are currently setting it with this code -
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
// Set new latitude and longitude values.
lookAt.setLatitude(43.023157);
lookAt.setLongitude(131.853040);
// Update the view in Google Earth.
ge.getView().setAbstractView(lookAt);
Try playing with different Latitude and Longitude numbers and you will see the difference.
You can also use stuff like lookAt.setRange, lookAt.setTilt and lookAt.setAltitude
See this link for more details
It has nothing to do with the .kml file you loaded.

Google annotated timeline not displaying on application start

I am having a problem with the Google annotated timeline. I have this function (shown below) that is called in the jQuery ready function:
//creates an annotated timeline
function graphAnnotatedTimeLine(url) {
jQuery.get(url, function(returned_data) {
//parse returned_data ...
//build data table
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('datetime', columnHeadings[0]);
dataTable.addColumn('number', columnHeadings[1]);
//populate table
for(var i = 0; i < rawData.length; i++) {
var parsedData = data[i].split(",");
dataTable.addRow([new Date(parsedData[0]), parseFloat(parsedData[1])]);
}
//draw graph
var options = {displayAnnotations: false,
allowRedraw: true,
legendPosition: 'newRow',
displayZoomButtons: false,
wmode: 'transparent'};
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart-div'));
chart.draw(dataTable, options);
});
}
Called in the ready function as:
$.ready(function() {
//generate url string
google.setOnLoadCallback(graphAnnotatedTimeline(url));
self.setInterval('updateGraph', 60000);
//more stuff
});
So in the ready I call it to draw the first set of data and then set an update function to be called every minute. All the update function does is basically the same as the ready function does: build a url string and call the graph function with that url. The problem I'm having is that the graph it doesn't display on startup. Once the update gets called once though, it displays fine after that. Is there anyone that can give me some insite as to why this is happening?
This is because your jquery ready function is called before the google visualization script is loaded. google.setOnLoadCallback must be called like this...
<script type="text/javascript" src='http://www.google.com/jsapi?autoload={"modules":[{"name":"visualization","version":"1","packages":["annotatedtimeline"]}]}'></script>
<script type="text/javascript">
google.setOnLoadCallback(graphAnnotatedTimeline(url));
</script>

Categories