How to set Cesium JS map center (coordinates: latitude & longitude) - javascript

I would like to initialize cesium so that the map is centered on some specific coordinates instead of the default ones. I have the following initialization code:
var map = new Cesium.CesiumWidget('map-js');
map.centralBody.terrainProvider = new Cesium.CesiumTerrainProvider({
url : 'http://cesiumjs.org/smallterrain'
});
Usually, with other mapping libraries, I would set the center on initialization, eg on mapbox:
map = L.mapbox.map('map-js', 'api-key').setView([42.12, 12.45], 9);
How to do that with cesium?

Try adding this after your first block of code above:
var scene = map.scene;
var ellipsoid = Cesium.Ellipsoid.WGS84;
var west = Cesium.Math.toRadians(-77.0);
var south = Cesium.Math.toRadians(38.0);
var east = Cesium.Math.toRadians(-72.0);
var north = Cesium.Math.toRadians(42.0);
var extent = new Cesium.Rectangle(west, south, east, north);
scene.camera.viewRectangle(extent, ellipsoid);
More examples are available in our Camera Demo.
EDIT (May 2014): Due to Cesium API changes, .getCamera() is renamed .camera, the camera's .controller was removed and rolled into the camera itself, and Extent is renamed to Rectangle. The above code now reflects the new API. For a complete list of breaking changes, see CHANGES.md.

If you want to keep the current "zoom" (aka camera distance from ellipsoid) and only have lon/lat, you could call setView() and use the current camera height, like:
viewer.camera.setView({
destination : Cesium.Cartesian3.fromDegrees(
longitude,
latitude,
Cesium.Ellipsoid.WGS84.cartesianToCartographic(viewer.camera.position).height
)
});

Related

Leaflet js map only showing a few tiles

I'm trying to create an custom stationary map using the Leaflet JavaScript library and keep running into a major issue where most of the map tiles for the coordinates do not render. I'm defining & showing the map like so
function initmap() {
map = new L.Map('map');
var osmUrl = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}.png';
var osm = new L.TileLayer(osmUrl);
map.addLayer(osm);
}
var lat = 40.120910;
var lng = -74.978602;
var startLatLng = new L.LatLng(lat, lng);
initmap();
map.setView(startLatLng, 16);
It seems like it should work, but the map div never shows the full map/all tiles. I know there is coverage for this particular area because I've been using another person's service that using this library and map to look at this location. This code is structured based off of their code.
This website is using the exact coordinates, map server, and the leaflet js script and is able to render all tiles fine.
Here's a JSFiddle to show the code (and issue) in action. Any idea why this is happening or how to fix it?
Missing Leaflet CSS: https://npmcdn.com/leaflet#1.0.0-rc.1/dist/leaflet.css
Updated JSFiddle: https://jsfiddle.net/t14rLknv/7/
(BTW you can upgrade to Leaflet 1.0.0-rc.3, new official CDN on unpkg.com, see http://leafletjs.com/download.html)

Leaflet.Geosearch: get lon/lat from address

Without any knowledge of JS, I was forced to implement a map (OSM via Leaflet) on a webpage. On this map, there should be a marker for the actual address of a person. The address is saved as a string in the database.
I can see a map, can add marker to it, but after that, I'm lost.
I've tested some Leaflet-geocoding-plugins, but i must confess, that they're not simple enough for my actual programmming experience.
Another question was about the same problem, but i didn't understand, how to get the lon/lat from an address with the L.Geosearch-plugin for Leaflet.
Can anyone provide me a example of looking up an address (via OSMN or something else, not google/bing or other api-key-needy provider), converting it to lon/lat and add a marker to it on a map?
First you will have to include the .js files of a geocoder in the head of your HTML code, for my example I have used this one: https://github.com/perliedman/leaflet-control-geocoder. Like this:
<script src="Control.Geocoder.js"></script>
Then you will have to initialize the Geocoder in your .js:
geocoder = new L.Control.Geocoder.Nominatim();
Then you will have to specify the address that you are looking for, you can save it in a variable. For example:
var yourQuery = (Addres of person);
(You can also get the address out of your database, then save it in the variable)
Then you can use the following code to 'geocode' your address into latitude / longitude. This function will return the latitude / longitude of the address. You can save the latitude / longitude in an variable so you can use it later for your marker. Then you only have to add the marker to the map.
geocoder.geocode(yourQuery, function(results) {
latLng= new L.LatLng(results[0].center.lat, results[0].center.lng);
marker = new L.Marker (latLng);
map.addlayer(marker);
});
I made a jfsfiddle that
Has an address set
Looks for the coordinates of that address using geosearch
Creates a marker at the coordinates of that address found by geosearch.
It can be found here: https://jsfiddle.net/Alechan/L6s4nfwg/
The "tricky" part is dealing with the Javascript "Promise" instance returned by geosearch and that the address may be ambigous and more than one coordinate may be returned in that case. Also, be careful because the first position in the Leaflet coordinates corresponds to the latitude and the second to the longitude, which is in reverse of the Geosearch "x" and "y" results.
Geosearch returns a promise because it's an asynchronous call. The alternative would have to be a synchronous call and the browser would have to be freezed until an answer was retrieved. More info about promises from MDM (Mozilla) and Google.
In my example, I create a marker for every result found for the indicated address. However, in this case the address is unambiguous and returns only one result.
Breakdown of code:
<!-- Head, imports of Leaflet CSS and JS, Geosearch JS, etc -->
<div id='map'></div>
<script>
// Initialize map to specified coordinates
var map = L.map( 'map', {
center: [ 51.5, -0.1], // CAREFULL!!! The first position corresponds to the lat (y) and the second to the lon (x)
zoom: 12
});
// Add tiles (streets, etc)
L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a','b','c']
}).addTo( map );
var query_addr = "99 Southwark St, London SE1 0JF, UK";
// Get the provider, in this case the OpenStreetMap (OSM) provider.
const provider = new window.GeoSearch.OpenStreetMapProvider()
// Query for the address
var query_promise = provider.search({ query: query_addr});
// Wait until we have an answer on the Promise
query_promise.then( value => {
for(i=0;i < value.length; i++){
// Success!
var x_coor = value[i].x;
var y_coor = value[i].y;
var label = value[i].label;
// Create a marker for the found coordinates
var marker = L.marker([y_coor,x_coor]).addTo(map) // CAREFULL!!! The first position corresponds to the lat (y) and the second to the lon (x)
// Add a popup to said marker with the address found by geosearch (not the one from the user)
marker.bindPopup("<b>Found location</b><br>"+label).openPopup();
};
}, reason => {
console.log(reason); // Error!
} );
</script>

OpenLayers not letting me add Popup

So I have (or had) a working version of OpenStreetMaps, but now that I want to add popups onto the map, the whole thing breaks. This is the code pertaining to the issue of the popup. The crazy thing is that I copy and pasted the code from the official wiki in order to just get a working example.
function init() {
map = new OpenLayers.Map( 'heatmapArea');
var query = new OpenLayers.LonLat(-122.2928337167, 37.5549570333).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var popup = new OpenLayers.Popup.FramedCloud("Popup", query, null, "Text", null, true);
map.addPopup(popup, false);
var lat = 39.3138895;
var lon = -98.2233523;
var zoom = 4;
var position = new OpenLayers.LonLat(lon, lat).transform( EPSG_WGS84, EPSG_900913);
map.setCenter(position, zoom );
}
The issue as it appears in my browser console is:
I have removed the code which I don't think is relevant to this issue but I could provide more if that is necessary. I have googled around extensively and all of the examples that I find work fine on the website I visit, but breaks my map and every StackOverflow answer to somebody else seems to work fine for the original poster, but once again, breaks my map.
Here's one of the website I tried to copy:
http://www.rigacci.org/openlayers/other_examples/markers.html
I am very eager to get this problem solved and any help would be greatly appreciated. Thanks!
-C.J.
Someone who really knows their way around the OL API will be able to explain this properly, but basically, your code is fine, but you need to reorder it. You need to add a map layer, and zoom to an extent, before you can call addPopup. I think this is because addPopup doesn't need an explicit layer of its own; it uses the map layer; and therefore you need a map layer on your map before trying to use it. That makes sense, but I am not sure why you need also to have called a zoom/zoomToExtent function.
Here's a fiddle, I've tried to leave your code as unchanged as possible:
http://jsfiddle.net/sifriday/u3j6h97d/3/
And here's the JS with some comments:
function init() {
var map = new OpenLayers.Map( 'heatmapArea');
// Add a map layer before trying to use addPopup
map.addLayer(new OpenLayers.Layer.OSM());
// Call the zoom function before trying to use addPopup
var lat = 39.3138895;
var lon = -98.2233523;
// I've changed the zoom to 1 so you can immediately see the popup in the small fiddle window
var zoom = 1;
var position = new OpenLayers.LonLat(lon, lat).transform(
"EPSG_WGS84", "EPSG_900913"
);
map.setCenter(position, zoom);
// Finally here's your addPopup code
var query = new OpenLayers.LonLat(
-122.2928337167, 37.5549570333
).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
var popup = new OpenLayers.Popup.FramedCloud(
"Popup",
query,
// I added a size to make it fit in the small fiddle window
new OpenLayers.Size(100,100),
"Text",
null,
true
);
map.addPopup(popup);
}

Google Earth API search by Placemarker Name

I am trying to create search box for Google Earth API Plugin for javascript
I am able to parse KMLFile and load in GE API and now I have to embed search by Placemarker name loaded by KML
Code using Lat & Long
var lookAt = ge.createLookAt('');
lookAt.set(point.y, point.x, 600, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 00, 0);
ge.getView().setAbstractView(lookAt);
Is there any possiblity for LookAt using Placemarker Name except using LAT, LONG?
Yes, there are lots of ways to look at placemarks. The easiest way to do this is if the placemark has and abstract view defined. e.g.
if (placemark.getAbstractView()) {
ge.getView().setAbstractView(placemark.getAbstractView());
}
You can also use the various accessors to refer to a placemark. For example if the placemark has an ID you can use getElementById.
var placemark = ge.getElementById('MyPlacemark');
if (placemark.getAbstractView()) {
ge.getView().setAbstractView(placemark.getAbstractView());
}
Or else if you are loading KML by its URL, e.g.
// loaded via KML
var placemark = ge.getElementByUrl('http://site.com/foo.kml#MyPlacemark');
if (placemark.getAbstractView()) {
ge.getView().setAbstractView(placemark.getAbstractView());
}
If the placemark doesn't have an abstract view you can still use the accessors to find the correct placemark and then extract the geometry from it to create the look at.
var placemark = ge.getElementByUrl('http://site.com/foo.kml#MyPlacemark');
var point = placemark.getGeometry();
var lat = point.getLatitude();
var lng = point.getLongitude();

Google Earth KmlModel Altitude

I am using the google earth plugin to manipulate a google earth window within my browser, however I can't seem to change altitude of KmlModels.
The offending script looks like this:
(mostly copied from an example)
var placemark = ge.createPlacemark('');
placemark.setName('model');
// Placemark/Model (geometry)
var model = ge.createModel('');
placemark.setGeometry(model);
// Placemark/Model/Link
var link = ge.createLink('');
link.setHref('http://earth-api-samples.googlecode.com/svn/trunk/examples/' +
'static/splotchy_box.dae');
model.setLink(link);
// get center look at location
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
// Placemark/Model/Location
var loc = ge.createLocation('');
loc.setLatitude(37.929828);
loc.setLongitude(-100.02596);
loc.setAltitude(6562); //Has no effect
model.setLocation(loc);
// add the model placemark to Earth
ge.getFeatures().appendChild(placemark);
// zoom into the model
lookAt.setRange(300);
lookAt.setTilt(80);
lookAt.setLatitude(37.929828);
lookAt.setLongitude(-100.02596);
ge.getView().setAbstractView(lookAt);
Does anyone know why? My model is always clamped to the ground no matter what. This is very frustrating.
add code:
model.setAltitudeMode (ge.ALTITUDE_RELATIVE_TO_GROUND);

Categories