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();
Related
I have a geoJson file with an array of coordinates that I am trying to make into a polyline on a map using leaflet.
My code worked initially but I then realised that the longitude and latitudes are reversed in my geoJson file, so this was taking me to different coordinates.
I tried to reverse these using the coordsToLatLngs() method but keeping getting an error that this method isn't defined as it's static:
Uncaught ReferenceError: coordsToLatLngs is not defined
[This is a link to the leaflet documentation on this section] 1https://leafletjs.com/reference-0.7.7.html#geojson
Any guidance as to how I can use this method so that I can switch the long and lat around?
My code for this section:
var latLngCoords = coordsToLatLngs(value.coords, 0, false);
var polyline = L.polyline(latLngCoords, {color: 'red'}).addTo(mymap);
mymap.fitBounds(polyline.getBounds());
```
coordsToLatLngs is not imported to global scope
try to run like this
L.coordsToLatLngs(value.coords, 0, false)
or
L.GeoJSON.coordsToLatLngs(value.coords, 0, false)
or, there is turf.js library https://turfjs.org/docs/#flip with flip function
let coords = turf.lineString(latLngCoords)
let newCoords = turf.flip(coords)
I have a bokeh Google maps plot with several Lat/ Lng data points, and I would like to use the fitBounds() method of the Google Maps v3 API to set the zoom level.
I have a Google Maps plot up and running, displaying on my site and showing the data points, but I need to set the zoom manually.
import bokeh.io
import bokeh.models
import bokeh.plotting
import pandas as pd
data = {
'Latitude [deg]': [18.46, 25.7, 32.3],
'Longitude [deg]': [-66, -80.2, -64.8],
}
data_frame = pd.DataFrame.from_dict(data)
data_source = bokeh.models.ColumnDataSource(data_frame)
mean_lat = data_frame['Latitude [deg]'].mean()
mean_lng = data_frame['Longitude [deg]'].mean()
gmap_options = bokeh.models.GMapOptions(lat=mean_lat, lng=mean_lng, zoom=10, map_type='satellite')
xy_gmap = bokeh.plotting.gmap('SuPeRSeCrEtAPIkey', gmap_options)
xy_gmap.circle(x='Longitude [deg]', y='Latitude [deg]', source=data_source, color="red")
# A callback like this? Could make the call in JavaScript after the page is loaded, and update map zoom??
# xy_gmap.fitBounds(x='Longitude [deg]', y='Latitude [deg]', source=data_source)
bokeh.io.show(xy_gmap)
I would like the bounds of the map to enclose all points in my dataframe, at the lowest zoom possible (as is done in Javascript by fitBounds() ). Currently, the map can only zoom to the manually set level.
As of Bokeh 1.2, there is no built-in way to accomplish this. The only suggestion I can offer is to note that there is a global Bokeh.index on the JavaScript side, and in that there is GMapPlotView for the corresponding GmapPlot that you made. This view has an attribute .map that is the actual Google map object. You could call the fitBounds method on that from JavaScript code. Bokeh GMapPlot objects follow Google's lead wrt to plot bounds, so if they get updated, the axes, etc. should respond.
Otherwise, I can only suggest opening a GitHub issue to discuss adding this as a new feature.
Starting an answer for both methods described by bigreddot (using JS Bokeh.index and Python integration)
Bokeh.index
In the Javascript Console, you can use the following commands (should be self explanatory to get this into some JS code)
> var gmapPlotView;
> for (var property in Bokeh.index) { if (Bokeh.index[property].constructor.name == 'GMapPlotView') {gmapPlotView = Bokeh.index[property];} } // Get the correct object, in the case that you have multiple plots, but only one map plot
> var bounds = gmapPlotView.map.getBounds(); // To start from existing bounds
> var bounds = google.maps.LatLngBounds(); // To start with fresh bounds
> var place = new google.maps.LatLng(45.5983128 ,8.9172776); // Coordinates of place to put bounds, repeat for all points
> bounds.extend(place); // Add each place to the bounds object
> gmapPlotView.map.fitBounds(bounds); // Set the maps new bounds
Note that the Bokeh google maps implementation does not plot your data on the Google Maps data layer, but on a bokeh canvas above the map (that is why there is a lag when panning the map between map tiles and your graphs).
Python Integration
In process....
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)
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>
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);