If you want to import a json file in your system to a vector layer, is as easy as:
var restaurantsold = new ol.layer.Vector({
title: 'b_layer',
source: new ol.source.Vector({
url: 'restaurantjson.geojson',
format: new ol.format.GeoJSON()
}),
});
And I can add that layer directly to the map. But if I try to make a call to an API, I can't display it in the map, my best try has been this:
var restaurants;
$.ajax({
type: "GET",
url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita",
dataType:"json",
success:function(data){
console.log(data)
restaurants = data;
$(restaurants).each(function(index, value) {
console.log(value.address);
});
}
});
var resta2 = new ol.layer.Vector({
title : "Resta2",
source: new ol.source.Vector(restaurants)
});
And I can't find a proper solution anywhere for this, thanks for your help!
EDIT:
at the end the problem was that it gets a JSON file, and openlayers wants an GeoJSON file.. my way to solve it was to convert it to GeoJSON following this:
https://gis.stackexchange.com/questions/73756/is-it-possible-to-convert-regular-json-to-geojson
The Restaurant data might not be available at all when you are creating the vector layer since you are making an Ajax Call.
So convert the GeoJSON to collection of ol.Feature objects using ol.format.GeoJSON readFeatures() method. Then add it vector source using addFeatures() method.
Fix :
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON()
})
var restaurantsold = new ol.layer.Vector({
title: 'b_layer',
source : vectorSource
});
$.ajax({
type: "GET",
url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita",
dataType:"json",
success:function(data){
// If response is valid
var geojsonFormat = new ol.format.GeoJSON();
// reads and converts GeoJSon to Feature Object
var features = geojsonFormat.readFeatures(data);
vectorSource.addFeatures(features);
}
});
Related
Basic script to display a kml file on a tiled background with openlayer; I just switched from version 2 to 4.65, how can I zoom to the limits of the kml geometry ("vector" here) ?
var wmsSource = new ol.source.TileWMS({
url: "https://sedac.ciesin.columbia.edu/geoserver/wms",
params: {"LAYERS": "other:wwf-terrestrial-biomes", "TILED": true},
serverType: "geoserver"
});
var wmsLayer = new ol.layer.Tile({
opacity: 0.15,
visible: true,
source: wmsSource
});
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: "kml_file.kml",
format: new ol.format.KML()
})
});
var map = new ol.Map({
target: "map-canvas",
layers: [wmsLayer, vector],
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({units: "metric"}),
new ol.control.FullScreen()
]),
view: new ol.View({
center: ol.proj.transform([37.41, 8.82], "EPSG:4326", "EPSG:3857"),
zoom: 3
})
});
I'd like to replace the zoom: 3 and have the map centered and extended to the kml limits ?
Note : I used kmllayer.events.register("loadend", kmllayer, function(evt){map.zoomToExtent(kmllayer.getDataExtent())}); with OpenLayers2...
The following should do what you want
var vectorSource = vector.getSource();
vectorSource.once('change', function(e){
if (vectorSource.getState() === 'ready') {
var extent = vectorSource.getExtent();
map.getView().fit(extent);
}
});
Solution mainly adapted from How to get the extent of a GeoJSON vector source? (changed the variable name & removed second argument in map.getView().fit (required in the old time, now optional, not needed most of the time, like here)
OK, I need to declare the kml source as a separate new ol.source.Vectorvariable, here vectorSource, and read .getExtent() from this variable, not from the ol.layer.Vector :
var wmsSource = new ol.source.TileWMS({
url: "https://sedac.ciesin.columbia.edu/geoserver/wms",
params: {"LAYERS": "other:wwf-terrestrial-biomes", "TILED": true},
serverType: "geoserver"
});
var wmsLayer = new ol.layer.Tile({
opacity: 0.15,
visible: true,
source: wmsSource
});
var vectorSource = new ol.source.Vector({
url: "'.$kml_f.'",
format: new ol.format.KML()
});
var vector = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: "map-canvas",
layers: [wmsLayer, vector],
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({units: "metric"}),
new ol.control.FullScreen()
]),
view: new ol.View({
center: ol.proj.transform([37.41, 8.82], "EPSG:4326", "EPSG:3857"),
zoom: 4,
})
});
vector.once("change", function(e){
var extent = vectorSource.getExtent();
map.getView().fit(extent);
});
Thanks for your help !
I am trying to display a geojson file on an openlayers map. The openlayers map is already working, however I cannot figure out how to display the features from the geojson file. The example on their website is unfortunately not very helpful, as it is simply the geojson object being written directly into the file and then accessed later. I wish to take the features from a separate geojson file and display them on the map.
This is what I have so far, copied directly from the example:
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
What I need to know is how do I "open" the file and get the features from the geojson file (currently located at the url ..\public\geojson\federal_ridings.geojson) in place of the variable geojsonObject which is already there?
To add GeoJSON layer from external file replace:
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
with
var vectorSource = new ol.source.Vector({
url: '..\public\geojson\federal_ridings.geojson',
format: new ol.format.GeoJSON()
});
ol.format.GeoJSON documentation
Make sure federal_ridings.geojson is a valid JSON file
Demo
I am using kmllayers from the standard Google Dev site:
var ctaLayer = new google.maps.KmlLayer({
url: 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml'
});
ctaLayer.setMap(map);
How do you do error checking? In my example I have url with a get parameter to get a filtered response from a database whose return is a kml.
If I get a null response or a kml with no data, I want to redirect the page. How do I perform the check?
Per the documentation on KmlLayer, the KmlLayerStatus can be retrieved from the KmlLayer:
var ctaLayer = new google.maps.KmlLayer({
url: 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml'
});
google.maps.event.addListener(ctaLayer,'status_changed', function() {
if (ctaLayer.getStatus() != OK) {
alert("error loading KML, status="+ctaLayer.getStatus());
}
}
ctaLayer.setMap(map);
I am trying to write a module`to load a Stamen tile map under Require.js, but I'm unsure how to best use it with Require.
If you haven't seen Stamen maps before, their site is at Stamen Maps.
This is the code for the map view, view.js
define([
'jquery',
'underscore',
'backbone',
'maps',
'text!templates/map/view.html'
], function($, _, Backbone, maps, mapTemplate){
var mapView = Backbone.View.extend({
el: $(".map"),
displayMap: function() {
this.options = {
center: new maps.LatLng(-37.8, 144.9),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
this.render();
},
render: function(){
var compiledTemplate = _.template(mapTemplate);
var $el = $(this.el);
$el.html(compiledTemplate);
this.map = new maps.Map($el.find('.map').get(0), this.options);
}
});
return new mapView;
});
I am loading the maps API following modules:
map.js
define(['google!maps/3/sensor=false'], function() {
return google.maps;
});
Which has the dependency of google.js
define(['http://www.google.com/jsapi?key=THE_API_KEY&callback=define'], {
load: function( name, req, load, config ) {
if (config.isBuild) {
onLoad(null);
} else {
var request = name.split('/');
google.load(request[0], request[1], {
callback: load,
language: 'en',
other_params: ((typeof request[2] === 'string')?request[2]:'')
});
}
}
});
The issue is that the Stamen maps layers appear to edit the Google Maps instance directly. You can see the Stamen maps implementation here:
http://maps.stamen.com/js/tile.stamen.js?v1.1.1
google.maps.StamenMapType = function(name) {
//Implementation
}
It seems to rely on the global google.maps object, which is where I believe the issue is coming from.
I'm unsure how to best rewrite the Stamen plugin to be require.js friendly, or if I need to, and I am really keen on using it. Unless I take Google Maps and Stamen out of Require.js and load them normally (like I do with Modernizr) but I'd much prefer to try and do it the Require.js way. If there is such a thing.
Any advice or tips would be much appreciated.
I'm responsible for tile.stamen.js. Sorry for the headache.
The problem here is that our script needs access to the Google Maps namespace (google.maps) so that it can create the StamenMapType class and have it inherit methods from Google's ImageMapType. If you absolutely need to use RequireJS (which I wouldn't suggest, exactly because it makes simple stuff like this awkward), you'll need to rewrite the whole Google-specific portion of tile.stamen.js (lines 155-177) to look something like this:
exports.makeStamenMapType = function(name, gmaps) {
if (!gmaps) gmaps = google.maps;
var provider = getProvider(name);
return new gmaps.ImageMapType({
"getTileUrl": function(coord, zoom) {
var index = (zoom + coord.x + coord.y) % SUBDOMAINS.length;
return [
provider.url
.replace("{S}", SUBDOMAINS[index])
.replace("{Z}", zoom)
.replace("{X}", coord.x)
.replace("{Y}", coord.y)
];
},
"tileSize": new gmaps.Size(256, 256),
"name": name,
"minZoom": provider.minZoom,
"maxZoom": provider.maxZoom
});
};
Then you'd use:
var toner = makeStamenMapType("toner", gmaps);
where gmaps is your required Google Maps API object.
I'm new to the Google Maps API and I'm working on localhost.
I want to add the ability for a user to upload their .gpx file and visualize it on the Google Map.
I've found this AJAX function wich works fine when I hardcode the .gpx file, but when I try to import the file from my computer, I got a grey screen for short second which then disappears.
Any idea or solution for this problem is more than welcome.
Thanks in advance.
function get_file() {
var fileInput = document.getElementById("file_upload");
var filename = fileInput.value;
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
loadGPXFileIntoGoogleMap(map, filename);
}
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: "xml",
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour("#ff0000"); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
There is no way to access filesystem from JavaScript.
This is a security issue. To resolve your issue I can see only one option: You should have server-side functionality that will temporary store user uploaded data. And then you can load user defined .gpx files from server.