Am I calling the JavaScript file correctly? - javascript

I have a web page and I was wondering if I am calling correctly javascript3.js. The file is inside the same folder as the html. When I put the javascript code inside the html, it works fine.
(The ol3-layerswitcher.js is being called correctly so I don't know why the other one is not being called.)
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css">
<link rel="stylesheet" href="ol3-layerswitcher.css">
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
<script src="ol3-layerswitcher.js"></script>
<script src="javascript3.js"></script>
</head>
<body>
<div id="map" style="width:100%;"></div>
<div id="info"></div>
</body>
</html>
javascript3.js:
var testSource = new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/wms',
params: {'LAYERS': 'Marine:Great_Britain', 'TILED': true},
serverType: 'geoserver'
});
var layers = [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'osm'})
}),
new ol.layer.Group({
title: 'Layers',
layers: [
//Implementing layers
new ol.layer.Tile({
title: 'Great Britain',
source: testSource
}),
]
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
center: [51480.6, 7216744.2], //UK
zoom: 5
})
});
//Function to get features from layer
map.on('singleclick', function(evt) {
document.getElementById('info').innerHTML = '';
viewResolution = map.getView().getResolution();
var url = testSource.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, 'EPSG:3857',
{'INFO_FORMAT': 'text/html'});
if (url) {
document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>';
}
});
//Layer switcher to turn layers on and off
var layerSwitcher = new ol.control.LayerSwitcher({
tipLabel: 'Legend'
});
map.addControl(layerSwitcher);

If you need to execute DOM manipulation without wrapping your code into document ready handler (such as $(document).ready();), the correct place is at the end of body (or at least after creating the DOM elements to be manipulated):
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css">
<link rel="stylesheet" href="ol3-layerswitcher.css">
<script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
<script src="ol3-layerswitcher.js"></script>
</head>
<body>
<div id="map" style="width:100%;"></div>
<div id="info"></div>
<script src="javascript3.js"></script>
</body>
</html>

Related

OpenLayers map.addLayer TypeError

I'm trying to do some simple drawing on OpenStreetMap data using OpenLayers (version 6.5.0). The map loads fine. I try to do the drawing when the button in the top right is clicked.
I convert this array of GPS coordinates into a Polygon, into a Feature, into an ol.source.Vector, into an ol.layer.Vector. I log every object constructed along the way on the console. This appears to go fine.
I finally want to add the (Vector) layer to the existing map using the .addLayer() function.
At this point, things go wrong inside the OpenLayer 6.5.0 JavaScript code. Deep inside the ol.js code, it throws a TypeError: t.addEventListener is not a function.
Browser screenshot
I've looked at multiple examples:
https://openlayers.org/en/latest/examples/polygon-styles.html
https://openlayers.org/en/latest/examples/geojson.html
So far, I have no clue whether this a bug in OpenLayer 6.5.0 or I'm missing something during conversion of my GPS coordinates array into an ol.layer.vector object. Any hints on this?
Entire html/javascript code below:
<meta charset="UTF-8">
<html>
<head>
<title>OSM test</title>
<link rel="stylesheet" href="ol.css">
<script src="ol.js"></script>
<script type="text/javascript">
function loadMap(domDivId, szLat, szLon, zoom) {
var vView = new ol.View({
center: ol.proj.fromLonLat([szLon, szLat]),
zoom: zoom
});
var lTile = new ol.layer.Tile({
source: new ol.source.OSM()
})
var map = new ol.Map({
target: domDivId,
layers: [lTile],
view: vView
});
return map;
}
function drawBermuda(map) {
// Bermuda triangle (approximate) GPS coordinates in [lat,lon] format
var arPath = [
[18.472282,-66.123934], // Bermuda
[32.297504,-64.778447], // Puerto Rico
[25.732447,-80.133221], // Miami
[18.472282,-66.123934] // Bermuda
];
console.log(arPath);
var pPath = {
'type': 'Polygon',
'coordinates': arPath
};
console.log(pPath);
var fPath = {
'type': 'Feature',
'geometry': pPath
};
console.log(fPath);
var svPath = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(fPath)
});
console.log(svPath);
var lvPath = new ol.layer.Vector({
source: svPath,
});
console.log(lvPath);
map.addLayer([lvPath]);
}
</script>
</head>
<body>
<div id="div_map" style="width:100%; height:100%; position:absolute; left:0px; top:0px; margin:0px; padding;0px; z-index:-10"></div>
<script>
map = loadMap('div_map', 25.0, -71.0, 5);
</script>
<div style="float:right">
<button onclick="drawBermuda(map);" style="height:100;width:100px;">click me please :-)</button>
</div>
</body>
</html>
P.S. I am aware that I still may have to swap latitude and longitude and convert the coordinates in some other way for OpenLayer to interpret them correctly. But that's not the main point here. I guess...
As well as missing and misplaced [ ] geojson coordinates must be specified in lon, lat order and features must be read into the view projection
<meta charset="UTF-8">
<html>
<head>
<title>OSM test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/css/ol.css" type="text/css">
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/build/ol.js"></script>
<script type="text/javascript">
function loadMap(domDivId, szLat, szLon, zoom) {
var vView = new ol.View({
center: ol.proj.fromLonLat([szLon, szLat]),
zoom: zoom
});
var lTile = new ol.layer.Tile({
source: new ol.source.OSM()
})
var map = new ol.Map({
target: domDivId,
layers: [lTile],
view: vView
});
return map;
}
function drawBermuda(map) {
// Bermuda triangle (approximate) GPS coordinates in [lon,lat] format
var arPath = [[
[-66.123934, 18.472282], // Bermuda
[-64.778447, 32.297504], // Puerto Rico
[-80.133221, 25.732447], // Miami
[-66.123934, 18.472282] // Bermuda
]];
var pPath = {
'type': 'Polygon',
'coordinates': arPath
};
var fPath = {
'type': 'Feature',
'geometry': pPath
};
var svPath = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(fPath, {featureProjection: map.getView().getProjection()})
});
var lvPath = new ol.layer.Vector({
source: svPath,
});
map.addLayer(lvPath);
}
</script>
</head>
<body>
<div id="div_map" style="width:100%; height:100%; position:absolute; left:0px; top:0px; margin:0px; padding;0px; z-index:-10"></div>
<script>
map = loadMap('div_map', 25.0, -71.0, 5);
</script>
<div style="float:right">
<button onclick="drawBermuda(map);" style="height:100;width:100px;">click me please :-)</button>
</div>
</body>
</html>

loading google maps in windows phone 8.1 using webview

I have created a sample app to load google maps in windows phone 8.1. Using the webview approch I'm not able to launch google maps, please help me in fixing this.. Below is the code:
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Maps</title>
<!-- WinJS references -->
<!-- At runtime, ui-themed.css resolves to ui-themed.theme-light.css or ui-themed.theme-dark.css
based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- Maps references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<h1>Google Maps API on Windows phone 8.1</h1>
<x-ms-webview id="Map" src="ms-appx-web:///map.html" style="width:500px;height:500px;"></x-ms-webview>
</body>
</html>
maps.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- map references -->
<link href="/map.css" rel="stylesheet" />
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
<script src="/map.js"></script>
</head>
<body>
<div id="mapdisplay" height="500px" width="500px"></div>
</body>
</html>
maps.js:
var map;
var dataResults;
function initialize() {
map = new google.maps.Map(document.getElementById('mapdisplay'), {
zoom: 3,
center: new google.maps.LatLng(40, -187.3),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
addMarkers();
}
eqfeed_callback = function (results) {
dataResults = results;
}
function addMarkers() {
for (var i = 0; i < dataResults.features.length; i++) {
var quake = dataResults.features[i];
var coors = quake.geometry.coordinates;
var latLong = new google.maps.LatLng(coors[1], coors[0]);
var marker = new google.maps.Marker({
position: latLong,
map: map
//icon: getCircle(earthquake.properties.mag)
});
}
}
function getCircle(magnitude) {
return {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'red',
fillOpacity: .2,
scale: Math.pow(2, magnitude) / Math.PI,
strokeColor: 'white',
strokeWeight: .5
};
}
What's the mistake I'm doing in the above code, please let me know..
"maps.html" does not work because of multiple synchronicity issues.
Load maps.js beforehttp://maps.googleapis.com/maps/api/js so initialise is defined,
Load http://maps.googleapis.com/maps/api/jsand after the HTML has been parsed so the mapdisplay element exists when initialise is called.
Call addMarkers from eqfeed_callback not initialise so dataResults has been set with valid object data.
Most of this could have been found out by opening the developers console and checking it for errors when viewing "maps.html" in a desktop browser. You may also like to research other questions on the topic and/or check the api documentation for working examples - and notice how the api documentation uses defer and async attributes on the script tag to make sure it doesn't execute until after the page has been parsed.

Issue calling Google API in Liferay

I have problem with the execution of the javascript inside a jsp page.
I have the following page which works perfectly if I call it from my filesystem, that is, I write in the address bar C:\...\heatmap2.jsp.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Energy Heatmap </title>
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 80% }
h1 { position:absolute; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true?key=AIzaSyCzoFE1ddY9Ofv0jjOvA3yYdgzV4JvCNl4"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type='text/javascript'>
/*Array in cui saranno inseriti i punti da visualizzare nella mappa
*/
var heatMapData = new Array();
function loadHeatMapData(callback)
{
$.ajax
({
type: "GET",
url: "http://localhost:8080/EnergyManagement-portlet/api/secure/jsonws/sample/get-samples-time-by-name?energyName=EnAssGS",
dataType: "jsonp",
crossDomain: true,
cache: false,
success: function(jsonData)
{
for (var i = 0; i < jsonData.length; i++)
{
var decodedData = JSON.parse(jsonData[i]);
var lng = decodedData["_longitude"];
var lat = decodedData["_latitude"];
var energyIntensity = decodedData["_value"];
heatMapData.push({location: new google.maps.LatLng(lat, lng), weight: energyIntensity});
}
return callback(heatMapData);
}
})
}
function drawHeatMap()
{
// map center
var myLatlng = new google.maps.LatLng(40.8333333, 14.25);
// map options,
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
// standard map
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var heatMap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
dissipating: false
});
heatMap.setMap(map);
/*
Questi punti dovrebbero prevenire da un file.
*/
var vehiclePath = [
new google.maps.LatLng(40.85235, 14.26813),
new google.maps.LatLng(40.85236, 14.26822),
new google.maps.LatLng(40.85236, 14.26822),
new google.maps.LatLng(40.85236, 14.26816),
new google.maps.LatLng(40.85258, 14.26811),
new google.maps.LatLng(40.85364, 14.26793),
new google.maps.LatLng(40.85414, 14.26778),
new google.maps.LatLng(40.8554, 14.2676),
new google.maps.LatLng(40.8579, 14.27286),
new google.maps.LatLng(40.85821, 14.27291),
new google.maps.LatLng(40.8584, 14.27302),
new google.maps.LatLng(40.85859, 14.27325),
new google.maps.LatLng(40.8587, 14.27421),
new google.maps.LatLng(40.85865, 14.27433),
new google.maps.LatLng(40.85866, 14.27446),
new google.maps.LatLng(40.86656, 14.291),
new google.maps.LatLng(40.86653, 14.29102)
];
var path = new google.maps.Polyline({
path: vehiclePath,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
}
/*Callback*/
loadHeatMapData(drawHeatMap)
</script>
</head>
<body>
<div id="map-canvas"></div>
<p id="demo"></p>
</body>
</html>
Unfortunately, when I try to call it inside my Liferay portal, I can't see any javascript running.
The following code creates a heatmap (with the Google API), the points are obtained with an asynchronous call to the webserver
via SOAP (it's a method available from an entity of my project).
I also tried to add the tag
<header-portlet-javascript>
"https://maps.googleapis.com/maps/api/js?libraries=visualization sensor=true?key=AIzaSyCzoFE1ddY9Ofv0jjOvA3yYdgzV4JvCNl4"
</header-portlet-javascript>
with no sucess.
Any help is appreciated.
Without being able to test your code currently, I see two issues with it:
Your JSP contains <html>, <head> and <body> elements etc. These are not allowed in portlets and won't work the same way as in a standalone page
Further, your contains superfluous quotes.
<header-portlet-javascript>
"https://maps.googleapis.com/and/so/on"
</header-portlet-javascript>
I'd expect this to literally be added to the page, resulting in double quotes
<script type="text/javascript" src=""https://maps.googleapis.com/and/so/on""></script>
Obviously, this doesn't work. Please check what ends up on the generated page when you add your portlet to it. Also, remove the extra quotes and try again.
Deae Olaf,
I applied your advice to my code.
With the support of the internet explorer debbuger, I found out that the code inside the drawHeatmpaData is like being commented (please, look at the picture)
.
In order to prevent from you code being commented, I found that we cannot use // to comment,
because all the text even the code is treated as comment.
I replace all // with /**/ but it still does not work.

Streetlevel example not working

I can't make work the new Streetlevel Javascript example (http://developer.here.com/javascript-apis/documentation/v3/maps/topics/panorama.html ).
I undestand the problem is "mapElement" in the constructor, but I can't figure out what is this parameter.
My app has a Base plan license.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width"/>
<script src="http://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-pano.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div style="width: 640px; height: 480px" id="basemap"></div>
<br> <script type="text/javascript" charset="utf-8">
// Create a Platform object:
var platform = new H.service.Platform({
'app_id': 'my_app_id',
'app_code': 'my_app_code'
});
var basemap = document.getElementById('basemap');
var maptypes = platform.createDefaultLayers()
// Configure panorama with platform credentials:
platform.configure(H.map.render.panorama.RenderEngine);
// Instantiate a map, giving the constructor the engine type to use:
map = new mapsjs.Map(mapElement, basemap, {
center: {lat: 48.8733641244471, lng: 2.294754032045603},
zoom: 19,
engineType: H.Map.EngineType.PANORAMA
});
</script>
</body>
</html>
I found a way to render the panorama:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width"/>
<script src="http://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-pano.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div style="width: 800px; height: 600px" id="basemap"></div>
<br>
<script type="text/javascript" charset="utf-8">
// Create a Platform object:
var platform = new H.service.Platform({
'app_id': 'my_app_id',
'app_code': 'my_app_code'
});
// Get an object containing the default map layers:
var defaultLayers = platform.createDefaultLayers();
// Configure panorama with platform credentials:
platform.configure(H.map.render.panorama.RenderEngine);
// Instantiate the map using the normal map as the base layer:
var map = new H.Map(document.getElementById('basemap'), defaultLayers.normal.panorama, {
center: {lat: 48.8733641244471, lng: 2.294754032045603},
zoom: 18,
engineType: H.Map.EngineType.PANORAMA
});
// Enable the event system on the map instance:
var mapEvents = new H.mapevents.MapEvents(map);
// Add event listeners:
map.addEventListener('tap', function(evt) {
// Log 'tap' and 'mouse' events:
console.log(evt.type, evt.currentPointer.type);
});
// Instantiate the default behavior, providing the mapEvents object:
var behavior = new H.mapevents.Behavior(mapEvents);
</script>
</body>
</html>

Javascript error of init() not defined . How to remove this error?

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="http://openlayers.org/api/2.10/OpenLayers.js" type="text/javascript">
var map, layer;
function init(){
map = new OpenLayers.Map( 'map', {controls: [
new OpenLayers.Control.Navigation({documentDrag: true}),
new OpenLayers.Control.PanZoom(),
new OpenLayers.Control.ArgParser(),
new OpenLayers.Control.Attribution()
]} );
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{layers: 'basic'} );
map.addLayer(layer);
map.zoomToMaxExtent();
}
</script>
</head>
<body onload="init()">
<h1 id="title">OpenLayers Document Drag Example</h1>
<div id="tags">
drag
</div>
<div id="shortdesc">Keep on dragging even when the mouse cursor moves outside of the map</div>
<div id="map" class="smallmap"></div>
<div id="docs">
<p>This example shows how to make a map draggable outside of the map itself.</p>
</div>
</body>
</html>
That is my html code with the javascript . My firebug throws up the error init() not defined . What can be the error ?
Your <script> element loads its content from an external resource (http://openlayers.org/api/2.10/OpenLayers.js) since you specified that URL in its src attribute.
Therefore, the browser will ignore the actual content of the element, so init() won't be defined.
Try using two <script> elements instead:
<script src="http://openlayers.org/api/2.10/OpenLayers.js" type="text/javascript">
</script>
<script type="text/javascript">
var map, layer;
function init(){
map = new OpenLayers.Map( 'map', {controls: [
new OpenLayers.Control.Navigation({documentDrag: true}),
new OpenLayers.Control.PanZoom(),
new OpenLayers.Control.ArgParser(),
new OpenLayers.Control.Attribution()
]} );
layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://vmap0.tiles.osgeo.org/wms/vmap0",
{layers: 'basic'} );
map.addLayer(layer);
map.zoomToMaxExtent();
}
</script>
This might help:
http://openlayers.org/dev/examples/lite.html
It is the basic and simplest example of Openlayers.

Categories

Resources