Can't get relative URL's working in OpenLayers3 - javascript

After three days of vainly looking everywhere (learning books OpenLayers3, Javascript and Internet) for a solution I put my question here.
The problem is that I can't get relative url's working in OpenLayers3. Here I give an example:
I have a OpenLayersscript in a map/directory called sandbox.
The relative url's in the HTML part of this script are working, including the relative url in javascript to ol.js.
The problem is that the relative url in the Javascript part of the script don't work. Only when the targetfile (nutsv9_lea.geojson) is in a map/directory underlying the map/directory containing the OpenLayersscript itself, it works, but only in Firefox and not in Google Chrome and InternetExplorer.
The map sandbox (containing this OpenLayersfile) is located in the maps/directories structure: C:/ol3_samples/sandbox
The targetfile (nutsv9_lea.geojson) is located in the maps/directories structure: C:/ol3_samples/assets/data/nutsv9_lea.geojson
The relative url I use is: url: '../assets/data/nutsv9_lea.geojson'
The only working solution (as mentioned above only in Firefox) is the relative url targeting to a underlying map/directory called 'data' containing the target file: url: 'data/nutsv9_lea.geojson' in the map/directory structure: C:/ol3_samples/sandbox/data/nutsv9_lea.geojson
What am I doing wrong or am I overlooking?
<script>
var vectorSource = new ol.source.GeoJSON({
projection: 'EPSG:3857',
//not working relative url:
// url: '../assets/data/nutsv9_lea.geojson'
//working url (with the targetfile in a directory below the directory containing this script) but only working in Firefox and not working in Chrome and InternetExplorer
url: 'data/nutsv9_lea.geojson'
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var center = ol.proj.transform([5.231819, 52.091852], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 5
});
var map = new ol.Map({
target: 'map',
layers: [vectorLayer],
view: view
});
</script>

I'm one of the authors of the book where this extract comes from. You need to run a local server (where files are served via http:// and not file://).
You just need to look at p 117.
It tells you can run (as long as you have Python)
python -m SimpleHTTPServer
or in case you got the samples from Packt website, run (if you have node)
node index.js
For both NodeJS and Python, you have install instructions (pages 417 & 418),
For Python and people who do not own the book, go to http://docs.python-guide.org/en/latest/starting/installation/

Related

GeoXML3 is not defined and cannot view data from KML file on own server?

I have tried to follow the following example at, https://gist.github.com/webapprentice/8427539, which when ever I try to display their KML from an external link I am able to display the polygon correctly, however if I copy and past the KML into a file and place this file on my server I am not able to display the results for the KML file. This is true of any third party KML file. Interestingly, I've noted that the coordinate values are inverse, but whenever I switch these values using http://kmltools.appspot.com/geoconv the KML file still does not function properly. I assume that the KML information is valid, because when I enter the contents into the text box at http://display-kml.appspot.com/ the map to left displays my polygons correctly.
In order to find a solution, I have added geoxmlv3.js to my server and am trying to parse the KML file into a format that my maps can understand as I assume that my server is not able to render the KML file properly. You can view the results of the KML file below under the HTML & JavaScript. GeoXML gives me two errorrs: Missing catch or finally after try and geoXML3 is not defined. These errors do not make much sense to me as I have already decleared the file above in my code which you can see below.
In addition, I have had a mime type added to IIS where file extention is kml and type is application/vnd.google-earth.kml+xml. I believe that this mime type works because when the page is directed to the file, the file is downloaded as does any other third party KML file.
========= HTML & JavaScript ==========
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 90%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyAjC_rKyBOaIBHtTu39GjC8h4SFWxry-s4"></script>
<script src="/js/geoxmlv3.js"></script>
<script>
var map;
var mylocation = {
'latitude': 47.66,
'longitude': -122.355
}
function initialize() {
var myLatlng = new google.maps.LatLng( mylocation.latitude, mylocation.longitude );
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var myParser = new geoXML3.parser({map: map});
myParser.parse('/zoneManagers.kml');
// This needs to be the Full URL - not a relative URL
// var kmlPath = "zoneManagers.kml";
// // Add unique number to this url - as with images - to avoid caching issues during development
// var urlSuffix = (new Date).getTime().toString();
// var layer = new google.maps.KmlLayer(kmlPath + '?' + urlSuffix );
//layer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
===== KML File =====
https://www.dropbox.com/s/q4v8eru0o3zp8xq/zoneManagers.kml?dl=0
About not being able to display the results of the KML file when you host it on your server. What server are you talking about ? Are you talking about a dev server running for example on localhost, a server in your local LAN or a public server accessible by anyone?
Are you using a fully-qualified URL for the KML like in the gist http://web-apprentice-demo.craic.com/assets/maps/fremont.kml ? Can the URL you're specifying be copy/pasted in any browser to access the file without any restrictions?
Google need to be able to access the KML file to process it and it's using the URL you're specifying to access it. If you're running on localhost, a private server or not specifying a public fully-qualified URL, Google can't access it.
If you're not doing that, you need to place the KML file on a public available domain and specify a fully-qualified public URL.
This option is not always possible if you're dealing with sensitive information, so your idea to use geoxml3 is the best option.
I have no problem running the code you provided and to successfully display the map & the KML file.
Since geoXML3 is not defined, I think it's possible you're not importing the file correctly.
Is your geoxmlv3.js in a js folder ?
Are you importing the correct file ? (source)
Did you rename the official file named geoxml3.js to geoxmlv3.js since you're trying to import /js/geoxmlv3.js and not /js/geoxml3.js ?
Is the js folder at the root of your server ? You may need to use js/geoxml3.js instead without the first /.
You can also check in your browser inspector (Network tab) that geoxmlv3.js is correctly loaded.
The 200 status code indicates that the geoxmlv3.js is correctly loaded.

Openlayers: Vector Layer from Local Variable

I am using OpenLayers to make a map from json data. I have to load it once already (with PHP) to check timestamps and verify information. At that point, I'd rather output a javascript variable and just have OL use that. I can't seem anything in the docs to accomplish this.
Ideally, I'd just change 'url': 'latest.json' to something like 'local': json_variable
var pointsSource = new ol.source.GeoJSON({
'projection': map.getView().getProjection(),
'url': 'latest.json'
});
var pointsLayer = new ol.layer.Vector({
source: pointsSource,
style: new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 40],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'openlayers/marker-icon.png',
}))
})
});
map.addLayer(pointsLayer);
You can pass in your geojson data via the param 'object'.
The OL3 src is quite readable and often it is faster to read this to work out what to do than it is to hunt through the docs! I'm assuming you're using ol3.4 or earlier; here is the 3.2 src code for geojson:
https://github.com/openlayers/ol3/blob/v3.2.0/src/ol/source/geojsonsource.js
You can see it takes an object param, which is expecting a JS object, which is the result of JSON.parse("...your geojson string here...")
So something like:
var geojson_cache = "<?php output from PHP here ?>"
var geojson_object = JSON.parse(geojson_cache)
var pointsSource = new ol.source.GeoJSON({
'projection': map.getView().getProjection(),
object: geojson_object
});
should do what you need.
Also FYI -- I mention OL3.4 or earlier above - the reason is that this class no longer exists in 3.5. You can see from that src file above that this class isn't much more than a wrapper around StaticVector with a ol.format.GeoJSON formatter attached. This has been refactored and will be replaced by ol.source.Vector and you provide the ol.format.GeoJSON formatter. Have a read of 'New Vector API' in these notes:
https://github.com/openlayers/ol3/releases/tag/v3.5.0

my .json file is not accessible from d3.json

Here is my script to create a line chart. The json file is not accessible from the d3.json () command. I am new to d3.js in general and I am using Dimple.js for plotting charts picking data from back end. I have also listed the json content below from my file.
var svg = dimple.newSvg("#charts", 800, 600);
d3.json("C:/dev/reports/data1.json", function (jsonfile) {
// Create a new chart object based on this data and svg
var myChart = new dimple.chart(svg, data);
myChart.addCategoryAxis("x", "Word");
myChart.addMeasureAxis("y", "Awesomeness");
myChart.addSeries(null, dimple.plot.line);
myChart.draw();
});
JSON content:
[
{ "Word":"Hello", "Awesomeness":2000 },
{ "Word":"World", "Awesomeness":3000 }
]
If you're using Chrome, it may prevent you from opening the file properly because of cross domain security restrictions. Try Firefox to see if that's the case (it will probably let you load the file correctly).
If that is the problem, you will want to install a local web server like WAMP (if you're running Windows) or follow instructions on the wiki page here.
It may help to use relative addressing to locate your data1.json file. if its in the same directory as your html file, just use;
d3.json("data1.json", function (jsonfile) {

OpenLayers.js which files to use?

As i red from the readme file, openlayers.js has multiple choices for including files and themes.
What i would like is to use the lightest solution of openlayers.js files.
I included the openlayers.light.js in my app, and it creates maps but do not show them, check this:
do i forgot to include some other file?
my structure structure is this:
/vendor
/js
openlayers.light.js
/img
/theme
how to show maps layers?
Also does the openlayers.light.js will work on mobile devices (once fixed this problem :P )? or i'll need to include openlayers.mobile.js too?
This is the code not working with openlayers.light.js but working with openlayers.js (740kb) :
var _element = "#map";
var map = new OpenLayers.Map (_element, {
controls: [
new OpenLayers.Control.Navigation({
dragPanOptions: {
enableKinetic: true
}
}),
new OpenLayers.Control.Zoom()
],
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326")
});
var lonLat = new OpenLayers.LonLat(_lon, _lat).transform (
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
// map.getProjectionObject() doesn't work for unknown reason
);
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon(_img_map_marker, size, offset);
markers.addMarker(new OpenLayers.Marker(lonLat, icon.clone()));
var mapnik = new OpenLayers.Layer.OSM("Test");
map.addLayer(mapnik);
map.setCenter (lonLat,3);
PS: my openlayers map js init method is ok, it works using the huge openlayers.js (740KB), but not working with openlayers.light.js as i showed above
html
<div id="map"></div>
css
img{max-width:none;}
#map{
width:300px;
height:300px;
}
if you want to use mobile properties with openlayers as panning or zooming with hand you have to use openlayers.mobile.js.
you can use openlayers.light.js with mobile devices but not mobile functions.
i think your structure should be :
myProject
/js
openlayers.light.js
/img
/theme
and i have tried openlayers.light.js in http://jsfiddle.net/aragon/ZecJj/ and there is no problem with it.
My code:
var map = new OpenLayers.Map({
div: "map",
minResolution: "auto",
maxResolution: "auto",
});
var osm = new OpenLayers.Layer.OSM();
var toMercator = OpenLayers.Projection.transforms['EPSG:4326']['EPSG:3857'];
var center = toMercator({x:-0.05,y:51.5});
map.addLayers([osm]);
map.setCenter(new OpenLayers.LonLat(center.x,center.y), 13);
and try to read Deploying (Shipping OpenLayers in your Application).
OpenLayers comes with pre-configured examples out of the box: simply
download a release of OpenLayers, and you get a full set of easy to
use examples. However, these examples are designed to be used for
development. When you’re ready to deploy your application, you want a
highly optimized OpenLayers distribution, to limit bandwidth and
loading time.
you can change src file with this link and can see it still works.
<script type="text/javascript" src="http://openlayers.org/dev/OpenLayers.light.debug.js"></script>
to
<script type="text/javascript" src="https://view.softwareborsen.dk/Softwareborsen/Vis%20Stedet/trunk/lib/OpenLayers/2.12/OpenLayers.light.js?content-type=text%2Fplain"></script>
i hope it helps you...

Using a local folder how to store google markers

var newIcon = new google.maps.MarkerImage('images/red-pushpin.png');
var newIcon = 'http://images/red-pushpin.png';
var newIcon = 'http://maps.google.com/mapfiles/ms/icons/red-pushpin.png';
var MarkerOption = {map:map, position:MarkerLatLng, title:name, icon:newIcon };
var Marker = new google.maps.Marker(MarkerOption);
I am using a VB WebBrowser Control to load an HTML page & access Google Maps via
javascript. It all works, except that I can only access the markers by line 3 above
but I want to use a local image folder (images) but javascrip cant 'see' it, yet
it is in the same directory as the HTML page.
What am I missing, please?
According to the MarkerOptions docs, the icon should be a URL.
So you will only be able to access an image within a url and local files embedded with file:/// tend to be ignored by browsers if the website is being served over http.
So only your 3 line is working.
If in case you want to access your icon image from the local drive, you can do it like this:
var newIcon= "http://mysite.com/images/red-pushpin.png"
In place of mysite replace it with the url that you get for your website when you run it

Categories