Here Maps polyline with altitude - javascript

I need to display different polylines from A to B. So, these lines should be distinguishable from each other. I haved tried to set polylines using pushpoint function with altitude parameter. However it is still on the ground level. And the last polyline I inserted overwrites the previous one.
Altitude value works on markers but I want to apply it on polyline.
I changed the sample code here markers with altitude as below. You can see the orange line is just on top of the gray line when you change the code with the below one. I would like both lines to be displayed like the markers you see above them.
/**
* Calculate the bicycle route.
* #param {H.service.Platform} platform A stub class to access HERE services
*/
function calculateRouteFromAtoB (platform) {
var router = platform.getRoutingService(),
routeRequestParams = {
mode: 'fastest;bicycle',
representation: 'display',
routeattributes : 'shape',
waypoint0: '-16.1647142,-67.7229166',
waypoint1: '-16.3705847,-68.0452683',
// explicitly request altitude values
returnElevation: true
};
router.calculateRoute(
routeRequestParams,
onSuccess,
onError
);
}
/**
* Process the routing response and visualise the descent with the help of the
* H.map.Marker
*/
function onSuccess(result) {
var lineString = new H.geo.LineString(),
lineString2 = new H.geo.LineString(),
routeShape = result.response.route[0].shape,
group = new H.map.Group(),
dict = {},
polyline,
polyline2;
routeShape.forEach(function(point) {
var parts = point.split(',');
var pp= new H.geo.Point(parts[0],parts[1],4000,"SL");
console.log(parts[2]);
lineString.pushLatLngAlt(parts[0], parts[1]);
lineString2.pushPoint(pp);
// normalize the altitude values for the color range
var p = (parts[2] - 1000) / (4700 - 1000);
var r = Math.round(255 * p);
var b = Math.round(255 - 255 * p);
// create or re-use icon
var icon;
if (dict[r + '_' + b]) {
icon = dict[r + '_' + b];
} else {
var canvas = document.createElement('canvas');
canvas.width = 4;
canvas.height = 4;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(' + r + ', 0, ' + b + ')';
ctx.fillRect(0, 0, 4, 4);
icon = new H.map.Icon(canvas);
// cache the icon for the future reuse
dict[r + '_' + b] = icon;
}
// the marker is placed at the provided altitude
var marker = new H.map.Marker({
lat: parts[0], lng: parts[1], alt: parts[2]
}, {icon: icon});
var marker2 = new H.map.Marker({
lat: parts[0], lng: parts[1], alt: parts[2]-800
}, {icon: icon});
group.addObject(marker);
group.addObject(marker2);
});
polyline = new H.map.Polyline(lineString, {
style: {
lineWidth: 6,
strokeColor: '#555555'
}
});
polyline2 = new H.map.Polyline(lineString2, {
style: {
lineWidth: 3,
strokeColor: '#FF5733'
}
});
// Add the polyline to the map
map.addObject(polyline);
map.addObject(polyline2);
// Add markers to the map
map.addObject(group);
// Zoom to its bounding rectangle
map.getViewModel().setLookAtData({
bounds: polyline.getBoundingBox(),
tilt: 60
});
}
/**
* This function will be called if a communication error occurs during the JSON-P request
* #param {Object} error The error message received.
*/
function onError(error) {
alert('Can\'t reach the remote server');
}
/**
* Boilerplate map initialization code starts below:
*/
// set up containers for the map + panel
var mapContainer = document.getElementById('map'),
routeInstructionsContainer = document.getElementById('panel');
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Berlin
var map = new H.Map(mapContainer,
defaultLayers.vector.normal.map,{
center: {lat:52.5160, lng:13.3779},
zoom: 13,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
calculateRouteFromAtoB (platform);

Unfortunately, for now only markers support altitudes.
Polylines should follow in near future.

Related

How to get MapMarker inside a polygon with clustering active

We're looking for a way to get our data points that are inside a polygon using JavaScript HereMaps API
We're adding 4 datapoints to a ClusterLayer / ClusterProvider and a polygon to the map. 3 of the 4 points are within the drawn Polygon (data of the points: a, b, d). Point with data = c is not within the polygon (see jsfiddle)
We tried to use map.getObjectsWithin but this functions only returns the polygon. We assume that this is caused by the different layers.
What's the best way to get the datapoints which are in the bounds of the polygon?
We try to avoid additional dependencies to solve this issue.
quick demo:
http://jsfiddle.net/4dno0gu2/59/
We found this question, but there wasn't any example, no activity for a long time and no solution.
HereMap getObjectsWithin does not show objects in LocalObjectProvider
Yeah the method getObjectsWithin doesn't work for ObjectProvider although this implemented in JS API but simple this functionality is not a public method, apologies for it.
Short description of workaround:
obtain the bounding box of the polygon
request all types of objects where you interested in for this bounding box from the provider
(requestOverlays, requestSpatials, requestMarkers etc.) - in your case requestMarkers
filter out all objects which doesn't intersect with the polygon
Code:
/**
* Adds a polygon to the map
*
* #param {H.Map} map A HERE Map instance within the application
*/
function addPolygonToMap(map) {
var geoStrip = new H.geo.LineString(
[48.8, 13.5, 100, 48.4, 13.0, 100, 48.4, 13.5, 100]
);
var polygon = new H.map.Polygon(geoStrip, {
style: {
strokeColor: '#829',
lineWidth: 8
},
data: 'polygon'
});
//map.addObject(polygon);
return polygon;
}
function logObjectsInPolygon(map, polygon){
var geoPolygon = polygon.getGeometry();
map.getObjectsWithin(geoPolygon, (o) => {
console.log('found mapObjects: '+ o.length);
o.forEach(x=>{
if(typeof x.getData === 'function'){
console.log(x.getData());
}
});
});
}
function isPointInPolygon(testPoint, polygPoints) {
let result = false;
let j = polygPoints.length - 1;
for(i=0,len=j+1; i<len; i++){
let p = polygPoints[i];
let lP = polygPoints[j];
if(p.y < testPoint.y && lP.y >= testPoint.y || lP.y < testPoint.y && p.y >= testPoint.y){
if((p.x + (testPoint.y - p.y) / (lP.y - p.y) * (lP.x - p.x)) < testPoint.x){
result = !result;
}
}
j = i;
}
return result;
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
var platform = new H.service.Platform({
apikey: 'H6XyiCT0w1t9GgTjqhRXxDMrVj9h78ya3NuxlwM7XUs',
useCIT: true,
useHTTPS: true
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Europe
var map = new H.Map(document.getElementById('map'),
defaultLayers.raster.normal.map,{
center: {lat:48.5, lng:13.45},
zoom: 10
});
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
//this marker should go to clusters if there is more data points
var dataPoints = [];
dataPoints.push(new H.clustering.DataPoint(48.5, 13.45,{}, 'a'));
dataPoints.push(new H.clustering.DataPoint(48.5001, 13.45,{}, 'b'));
dataPoints.push(new H.clustering.DataPoint(48.5002, 13.51,{}, 'c')); // not in Polygon
dataPoints.push(new H.clustering.DataPoint(48.53, 13.45,{}, 'd'));
var clusteredDataProvider = new H.clustering.Provider(dataPoints);
var layer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(layer);
// createPolygon to select clustered (noise) points
var polygon = addPolygonToMap(map);
let extPoly = polygon.getGeometry().getExterior();
let seqPointsPoly = [];
extPoly.eachLatLngAlt((lat, lng, alt, idy) => {
seqPointsPoly.push( {y: lat, x: lng});
});
console.log("seqPointsPoly:", seqPointsPoly);
map.addEventListener("tap", (e) => {
let pBbox = polygon.getBoundingBox();
let arrPnts = clusteredDataProvider.requestMarkers(pBbox);
for(let i=0,len=arrPnts.length; i<len; i++){
let m = arrPnts[i];
let p = {y: m.getGeometry().lat, x: m.getGeometry().lng};
let clustData = m.getData();
if(!clustData.getData){
console.log("cluster: is in polygon:", isPointInPolygon(p, seqPointsPoly));
} else if(clustData.getData){
console.log("nois: is in polygon:", clustData.getData(), m.getGeometry(), isPointInPolygon(p, seqPointsPoly));
}else{
console.log("unknown type");
}
}
console.log("clusteredDataProvider:", pBbox, clusteredDataProvider.requestMarkers(pBbox));
// Our expected logging is: points a, b, d
//logObjectsInPolygon(map, polygon);
});
Worked example (tap on map to start processing): http://jsfiddle.net/m1ey7p2h/1/

How to curve a Polyline in react-google-maps?

I'm new to React and have been playing around with the react-google-maps package. I'm trying to curve a Polyline that joins two places. After going through the documentation, I'm trying to incorporate the curve polyline function under the 'editable' prop.
Here's the function to curve the polyline:
var map;
var curvature = 0.4; // Arc of the Polyline
function init() {
var Map = google.maps.Map,
LatLng = google.maps.LatLng,
LatLngBounds = google.maps.LatLngBounds,
Marker = google.maps.Marker,
Point = google.maps.Point;
// Initial location of the points
var pos1 = new LatLng(this.state.srcMarker);
var pos2 = new LatLng(this.state.desMarker);
var bounds = new LatLngBounds();
bounds.extend(pos1);
bounds.extend(pos2);
map = new Map(document.getElementById('map-canvas'), {
center: bounds.getCenter(),
zoom: 12
});
map.fitBounds(bounds);
var markerP1 = new Marker({
position: pos1,
map: map
});
var markerP2 = new Marker({
position: pos2,
map: map
});
var curveMarker;
function updateCurveMarker() {
var pos1 = markerP1.getPosition(),
pos2 = markerP2.getPosition(),
projection = map.getProjection(),
p1 = projection.fromLatLngToPoint(pos1),
p2 = projection.fromLatLngToPoint(pos2);
// Calculating the arc.
var e = new Point(p2.x - p1.x, p2.y - p1.y), // endpoint
m = new Point(e.x / 2, e.y / 2), // midpoint
o = new Point(e.y, -e.x), // orthogonal
c = new Point( m.x + curvature * o.x, m.y + curvature * o.y); //curve control point
var pathDef = 'M 0,0 ' + 'q ' + c.x + ',' + c.y + ' ' + e.x + ',' + e.y;
var zoom = map.getZoom(),
scale = 1 / (Math.pow(2, -zoom));
var symbol = {
path: pathDef,
scale: scale,
strokeWeight: 1,
fillColor: 'none'
};
if (!curveMarker) {
curveMarker = new Marker({
position: pos1,
clickable: false,
icon: symbol,
zIndex: 0, // behind the other markers
map: map
});
} else {
curveMarker.setOptions({
position: pos1,
icon: symbol,
});
}
}
google.maps.event.addListener(map, 'projection_changed', updateCurveMarker);
google.maps.event.addListener(map, 'zoom_changed', updateCurveMarker);
google.maps.event.addListener(markerP1, 'position_changed', updateCurveMarker);
google.maps.event.addListener(markerP2, 'position_changed', updateCurveMarker);
}
google.maps.event.addDomListener(window, 'load', init);
I'm not able to understand how to use this function in the Polyline component. I'm able to mark a line between any two places, but not able to use this function in order to curve the given polyline. This is the Polyline component that I'm using.
<Polyline
path={pathCoordinates}
geodesic={true}
options={{
strokeColor: '#ff2527',
strokeOpacity: 1.0,
strokeWeight: 5,
}}
/>
I have two markers in my state (srcMarker, desMarker) that store the coordinates of the given cities once the user inputs the city name. Any help would be appreciated in incorporating this function with the Polyline component. I haven't come across any built in feature that allows curving of the polyline. Thanks in advance!
I took the code you provided and adapted it to work with React and react-google-maps. Check out this CodeSandbox to see a simple application that contains two markers and a curved line between them.
The curved line that connects the two markers is actually a marker as well. The only difference between it and the two red markers is that its icon prop is set to the curved line (which is computed beforehand).
Here is the code for the CurveMarker component:
const CurveMarker = ({ pos1, pos2, mapProjection, zoom }) => {
if (!mapProjection) return <div/>;
var curvature = 0.4
const p1 = mapProjection.fromLatLngToPoint(pos1),
p2 = mapProjection.fromLatLngToPoint(pos2);
// Calculating the arc.
const e = new google.maps.Point(p2.x - p1.x, p2.y - p1.y), // endpoint
m = new google.maps.Point(e.x / 2, e.y / 2), // midpoint
o = new google.maps.Point(e.y, -e.x), // orthogonal
c = new google.maps.Point(m.x + curvature * o.x, m.y + curvature * o.y); //curve control point
const pathDef = 'M 0,0 ' + 'q ' + c.x + ',' + c.y + ' ' + e.x + ',' + e.y;
const scale = 1 / (Math.pow(2, -zoom));
const symbol = {
path: pathDef,
scale: scale,
strokeWeight: 2,
fillColor: 'none'
};
return <Marker
position={pos1}
clickable={false}
icon={symbol}
zIndex={0}
/>;
};
Let me know if you have any questions.

How to Break up large Javascript file with RequireJS

I'm new to Javascript and therefore requireJS - I'm currently teaching myself using Openlayers 3 examples, of which, I've just been appending to one large JS file. Seeing that this is becoming unruly very quickly, I read up about RequireJS and thought I should get into the habit of doing things right from the onset; 'which is where I've hit issues'.
[Not that I imagine it matters, but i'm using Asp.net MVC]
Basically, I wish to break the file up into smaller related modules e.g.
Map [which is used by all modules and initiates the base layer map]
Draw [handles points / polygons etc. and is added to the map as
another layer]
Geolocation [contains geolocation functions for plotting]
etc., etc.
...giving the flexibility to have all layers activated at once, or a select few with easy to manage JS code.
I have had several attempts at breaking this code up into such individual JS files, [map / draw / Geolocation] and all fail as I feel I'm not grasping the requireJS methodology (so as not to confuse readers and myself further, I'm neglecting to add my attempts).
Here is the basic code that works:
require.config({
baseUrl: "/Scripts",
paths: {
//jquery: "/lib/jquery-1.11.1.min",
ol: [
"http://openlayers.org/en/v3.8.1/build/ol",
"/lib/ol"
],
domReady: "/lib/domReady"
},
//map: { main: { test: "/Modules/Test/scripts/test" } },
//The shim section is to tell RequireJS about any dependencies your files have before they can be used.
//Here, we are saying if we call “ol” to load that module, we have to load “jquery” first.
//shim: {
//ol: ["jquery"]
//},
//packages: [
// {
//name: 'test',
//location: 'http://...
//main: 'main'
//}]
});
File I wish to break-up:
define(["ol"], function (ol) {
$(document).ready(function () {
//****************
//------MAP-------
//Setup Map Base
// creating the view
var view = new ol.View({
center: ol.proj.fromLonLat([5.8713, 45.6452]),
zoom: 19
});
// creating the map
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: "map",
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: view
});
//****************
//-----DRAW------
var features = new ol.Collection();
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector({ features: features }),
style: new ol.style.Style({
fill: new ol.style.Fill({
color: "rgba(255, 255, 255, 0.2)"
}),
stroke: new ol.style.Stroke({
color: "#ffcc33",
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: "#ffcc33"
})
})
})
});
featureOverlay.setMap(map);
var modify = new ol.interaction.Modify({
features: features,
// the SHIFT key must be pressed to delete vertices, so
// that new vertices can be drawn at the same position
// of existing vertices
deleteCondition: function (event) {
return ol.events.condition.shiftKeyOnly(event) &&
ol.events.condition.singleClick(event);
}
});
map.addInteraction(modify);
var draw; // global so we can remove it later
function addInteraction() {
draw = new ol.interaction.Draw({
features: features,
type: /** #type {ol.geom.GeometryType} */ (typeSelect.value)
});
map.addInteraction(draw);
}
var typeSelect = document.getElementById("type");
/**
* Let user change the geometry type.
* #param {Event} e Change event.
*/
typeSelect.onchange = function (e) {
map.removeInteraction(draw);
addInteraction();
};
addInteraction();
//****************
//---GEOLOCATION---//
// Common app code run on every page can go here
// Geolocation marker
var markerEl = document.getElementById("geolocation_marker");
var marker = new ol.Overlay({
positioning: "center-center",
element: markerEl,
stopEvent: false
});
map.addOverlay(marker);
// LineString to store the different geolocation positions. This LineString
// is time aware.
// The Z dimension is actually used to store the rotation (heading).
var positions = new ol.geom.LineString([],
/** #type {ol.geom.GeometryLayout} */ ("XYZM"));
// Geolocation Control
var geolocation = new ol.Geolocation( /** #type {olx.GeolocationOptions} */({
projection: view.getProjection(),
trackingOptions: {
maximumAge: 10000,
enableHighAccuracy: true,
timeout: 600000
}
}));
var deltaMean = 500; // the geolocation sampling period mean in ms
// Listen to position changes
geolocation.on("change", function (evt) {
var position = geolocation.getPosition();
var accuracy = geolocation.getAccuracy();
var heading = geolocation.getHeading() || 0;
var speed = geolocation.getSpeed() || 0;
var m = Date.now();
addPosition(position, heading, m, speed);
var coords = positions.getCoordinates();
var len = coords.length;
if (len >= 2) {
deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
}
var html = [
"Position: " + position[0].toFixed(2) + ", " + position[1].toFixed(2),
"Accuracy: " + accuracy,
"Heading: " + Math.round(radToDeg(heading)) + "°",
"Speed: " + (speed * 3.6).toFixed(1) + " km/h",
"Delta: " + Math.round(deltaMean) + "ms"
].join("<br />");
document.getElementById("info").innerHTML = html;
});
geolocation.on("error", function () {
alert("geolocation error");
// FIXME we should remove the coordinates in positions
});
// convert radians to degrees
function radToDeg(rad) {
return rad * 360 / (Math.PI * 2);
}
// convert degrees to radians
function degToRad(deg) {
return deg * Math.PI * 2 / 360;
}
// modulo for negative values
function mod(n) {
return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI);
}
function addPosition(position, heading, m, speed) {
var x = position[0];
var y = position[1];
var fCoords = positions.getCoordinates();
var previous = fCoords[fCoords.length - 1];
var prevHeading = previous && previous[2];
if (prevHeading) {
var headingDiff = heading - mod(prevHeading);
// force the rotation change to be less than 180°
if (Math.abs(headingDiff) > Math.PI) {
var sign = (headingDiff >= 0) ? 1 : -1;
headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff));
}
heading = prevHeading + headingDiff;
}
positions.appendCoordinate([x, y, heading, m]);
// only keep the 20 last coordinates
positions.setCoordinates(positions.getCoordinates().slice(-20));
// FIXME use speed instead
if (heading && speed) {
markerEl.src = "/OrchardLocal/Media/Default/Map/geolocation_marker.png"; //"data/geolocation_marker_heading.png";F:\DeleteMeThree\_Orchard-19x\src\Orchard.Web\Modules\Cns.OL\Contents/Images/geolocation_marker.png
} else {
//alert(markerEl.src); PETE: Not sure if this is std OL practice, but this is achieved by already having an element
//called "geolocation_marker" in the dom as an img, which this uses? Strange to me
markerEl.src = "/OrchardLocal/Media/Default/Map/geolocation_marker.png"; //I added img via media module - ridiculous?!
}
}
var previousM = 0;
// change center and rotation before render
map.beforeRender(function (map, frameState) {
if (frameState !== null) {
// use sampling period to get a smooth transition
var m = frameState.time - deltaMean * 1.5;
m = Math.max(m, previousM);
previousM = m;
// interpolate position along positions LineString
var c = positions.getCoordinateAtM(m, true);
var view = frameState.viewState;
if (c) {
view.center = getCenterWithHeading(c, -c[2], view.resolution);
view.rotation = -c[2];
marker.setPosition(c);
}
}
return true; // Force animation to continue
});
// recenters the view by putting the given coordinates at 3/4 from the top or
// the screen
function getCenterWithHeading(position, rotation, resolution) {
var size = map.getSize();
var height = size[1];
return [
position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
position[1] + Math.cos(rotation) * height * resolution * 1 / 4
];
}
// postcompose callback
function render() {
map.render();
}
//EMP
//$("#geolocate").click(function () {
// alert("JQuery Running!");
//});
// geolocate device
var geolocateBtn = document.getElementById("geolocate");
geolocateBtn.addEventListener("click", function () {
geolocation.setTracking(true); // Start position tracking
map.on("postcompose", render);
map.render();
disableButtons();
}, false);
});
})
Considering that i'll have many more modules to attach in the future, what would be the best way to break-up this code using RequireJS for efficiency and coding functionality / maintenance.
Thanks ever so much for your guidance / thoughts, cheers WL
Every require module (defined using define) is supposed to return a function/object. The breakup shown in question doesn't, instead just splits the code. Think of some hypothetical module buckets and put each piece of code (or function) into a module. Then group the code into a require js module and return the module's interface.
Let me try to explain further with an example.
main.js
$(document).ready(function(){
$("#heyINeedMap").click(function(){
require(['map'],function(Map){
Map.render($target);
});
});
});
OR
$(document).ready(function(){
require(['map','geolocation'],function(Map,Geolocation){
window.App.start = true;
window.App.map = Map; //won't suggest, but you can do.
window.App.geolocation = Geolocation;
//do something.
$("#lastCoords").click(function(){
var coords = App.geolocation.getLastSavedCoords();
if(!!coords){
coords = App.geolocation.fetchCurrentCoords();
}
alert(coords);
});
});
});
map.js
define(['jquery'],function($){
var privateVariableAvailableToAllMapInstances = 'something';
var mapType = 'scatter';
return function(){
render: function(el){
//rendering logic goes here
},
doSomethingElse: function(){
privateVariable = 'some new value';
//other logic goes here
},
changeMapType: function(newType){
mapType = newType;
//...
}
}
});
geolocation.js
//Just assuming that it needs jquery & another module called navigation to work.
define(['jquery','navigation'], function($,Gnav){
return {
var coordinates = Gnav.lastSavedCoords;
fetchCurrentCoords: function(){
//coordinates = [79.12213, 172.12342]; //fetch from API/something
return coordinates;
},
getLastSavedCoords: function(){
return coordinates;
}
}
});
Hope this gives an idea on how to proceed.

how can I set markers with different colours depending on the markertype, and how to determinate their coordinates?, Im using openlayers.org library

I am starting using openlayers javascript library from openlayers.org.
I want to set dinamic markers with diferent colours for each device type(cam marker, server marker and so on), and I tried different ways to set this, but it doesn't work actually.
This is the map that Im developing: http://manotazsoluciones.com/map/.
Another problem that Im facing is when I set coordinates. For example: if I set [0,0] coordinates on a marker, when I use click event, the marker get another coordinates like
[30000,-7.081154551613622e-10].
this is the code that Im using to display the map on manotazsoluciones.com/map
<!DOCTYPE html>
<html>
<head>
<title>Manotaz Soluciones</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="col-md-10 col-md-offset-1">
<div id="map" class="map">
<div id="popup">
<div id="popup-content"></div>
</div>
</div>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
/**************** DRAG AND DROP EVENTS ****************/
/**
* Define a namespace for the application.
*/
window.app = {};
var app = window.app;
/**
* #constructor
* #extends {ol.interaction.Pointer}
*/
app.Drag = function() {
ol.interaction.Pointer.call(this, {
handleDownEvent: app.Drag.prototype.handleDownEvent,
handleDragEvent: app.Drag.prototype.handleDragEvent,
handleMoveEvent: app.Drag.prototype.handleMoveEvent,
handleUpEvent: app.Drag.prototype.handleUpEvent
});
/**
* #type {ol.Pixel}
* #private
*/
this.coordinate_ = null;
/**
* #type {string|undefined}
* #private
*/
this.cursor_ = 'pointer';
/**
* #type {ol.Feature}
* #private
*/
this.feature_ = null;
/**
* #type {string|undefined}
* #private
*/
this.previousCursor_ = undefined;
};
ol.inherits(app.Drag, ol.interaction.Pointer);
/**
* #param {ol.MapBrowserEvent} evt Map browser event.
* #return {boolean} `true` to start the drag sequence.
*/
app.Drag.prototype.handleDownEvent = function(evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if (feature) {
this.coordinate_ = evt.coordinate;
this.feature_ = feature;
}
return !!feature;
};
/**
* #param {ol.MapBrowserEvent} evt Map browser event.
*/
app.Drag.prototype.handleDragEvent = function(evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
var deltaX = evt.coordinate[0] - this.coordinate_[0];
var deltaY = evt.coordinate[1] - this.coordinate_[1];
var geometry = /** #type {ol.geom.SimpleGeometry} */
(this.feature_.getGeometry());
geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0];
this.coordinate_[1] = evt.coordinate[1];
};
/**
* #param {ol.MapBrowserEvent} evt Event.
*/
app.Drag.prototype.handleMoveEvent = function(evt) {
if (this.cursor_) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
var element = evt.map.getTargetElement();
if (feature) {
if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
}
};
/**
* #param {ol.MapBrowserEvent} evt Map browser event.
* #return {boolean} `false` to stop the drag sequence.
*/
app.Drag.prototype.handleUpEvent = function(evt) {
this.coordinate_ = null;
this.feature_ = null;
return false;
};
/*************** DRAG AND DROP EVENTS END *************/
You can ignore the drag and drop events above, because it works fine
var devices = [
{
'id' : 1,
'device' : 'cam',
'brand' : 'dahua',
'coordinates' : [0,0]
},
{
'id' : 2,
'device' : 'cam',
'brand' : 'vivotes',
'coordinates' : [0,1]
},
{
'id' : 3,
'device' : 'cam',
'brand' : 'dahua',
'coordinates' : [0, 2]
},
{
'id' : 4,
'device' : 'rack',
'brand' : 'dahua',
'coordinates' : [0, 3]
}
];
the code above is just an example of the resource that I want to display
var circle = [];
for (var i = 0; i < devices.length; i++) {
circle[i] = new ol.Feature(
new ol.geom.Circle(
ol.proj.transform(devices[i].coordinates, 'EPSG:4326', 'EPSG:3857'),//usar latitud, longitud, coord sys
30000
)
);
}
on var circle Im saving the coordinates and size for each marker.
var styles = [
new ol.style.Style({
image: new ol.style.Icon({ //#type {olx.style.IconOptions}
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 1,
population: 4000,
rainfall: 500
}),
fill: new ol.style.Fill({
color: [150, 150, 255, 1]
})
})
];
in styles im setting the color for all markers, but I want to change his values depending on the device type
// RENDER DEVICES
var objects = new ol.source.Vector({ features: circle })
var bullets = new ol.layer.Vector({
source : objects,
style: styles
});
above Im setting the markers and styles.
//layers-capaImagen, propiedades imagen principal
var extent = ol.proj.transformExtent([-50, 50, 50, -40], 'EPSG:4326', 'EPSG:3857');
var imgProjection = new ol.proj.Projection({
code: 'xkcd-image',
units: 'pixels',
extent: [0, 0, 1024, 968]
});
var capaImagen = new ol.layer.Image();
source = new ol.source.ImageStatic({
url: 'plano-vertical-knits.jpg',
imageExtent: extent,
projection: imgProjection,
center: ol.extent.getCenter(imgProjection.getExtent()),
extent: imgProjection.getExtent()
});
capaImagen.setSource(source);
//end propiedades imagen principal
//map features before render
var features = {
controls : ol.control.defaults({attribution : false}).extend([ new ol.control.FullScreen() ]),
interactions: ol.interaction.defaults().extend([new app.Drag()]),
layers : [capaImagen, bullets],
view: new ol.View({ center: [0, 0], zoom: 3 }),
target : 'map'
};
var map = new ol.Map(features);
above Im rendering the map with their features
// display popup on click
var pops = document.getElementById('popup');
var popupContent = document.getElementById('popup-content');
var popup = new ol.Overlay({/** #type {olx.OverlayOptions} */
element: pops,
autoPan: true,
stopEvent: false,
positioning: 'bottom-center',
autoPanAnimation: {
duration: 250
}
});
map.addOverlay(popup);
/* events ON map */
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return feature;
});
if (feature) {
var geometry = feature.getGeometry();
var firstCoord = geometry.getFirstCoordinate();
var lastCoord = geometry.getLastCoordinate();
popup.setPosition(firstCoord);
$(pops).popover({
'placement': 'top',
'html': true,
'content': feature.get('name')
});
//var latlong = ol.proj.transform([firstCoord, lastCoord], 'EPSG:4326', 'EPSG:3857');
popupContent.innerHTML = '<p>You clicked here:</p><p>'+lastCoord+'</p>';
$(pops).popover('show');
}
});
// change mouse cursor when over marker
map.on('pointermove', function(e) {
if (e.dragging) {
$('#popup-content').empty();
return;
}
});
/* events ON map END */
});
</script>
</body>
</html>
on click function Im trying to get the coordinates, and is where the coordinates shows me another values.
I extracted some of your codes and I added some modifications.
Style problem
Each feature needs to have a reference to the properties that you saved in array devices:
for (var i = 0; i < devices.length; i++) {
circle[i] = new ol.Feature(
{geometry: new ol.geom.Circle(
ol.proj.transform(devices[i].coordinates, ), 'EPSG:4326', 'EPSG:3857'),//usar latitud, longitud, coord sys
1
),
device: devices[i].device}
);
}
Additionally, it is necessary to set a different style for each desired property. Something like that should work:
var bullets = new ol.layer.Vector({
source: objects,
style: function (el, resolution) {//this is a style function
console.log(el, el.getProperties().device);
if (el.getProperties().device === 'cam')
return styles;
return styles2;
}
});
Problem with the coordinates
I think the problem in this case is due to the projection. You defined a custom projection (based on pixel) and applied it to the image. For the map view you don't define any projection (so it remains the default EPSG:3857). All the coordinates of the circle are converted from 'EPSG:4326' to 'EPSG:3857'. Therefore, the values that you see in the popup are in EPSG:3857 (not longitude and latitude). If you decide to continue to use EPSG:3857, you should also adapt the static image to this coordinates system via:
source = new ol.source.ImageStatic({
...............
imageExtent: .....
As you can find in the documentation imageExtent is the extent of the image in map coordinates. But in your code imageExtent is just the extent in pixel of the image.......

Google Maps API - Overlay Custom Roads

I am having a few issues with the Google Maps API. I managed to make a cutom map using an image tile. which seems to be working OK. I am just wondering if there is a way to overlay roads on the map?
At the moment I am assuming there are 2 ways this is possible, either some built in function in the API, which I am having troubles finding. I have found paths etc, But I would like roads/streets to have labels, resize on zoom etc, as well as be able to toggle.
The other option was to do a second image tile and overlay that image, which I am not sure how todo at this moment.
If anyone has any info on this, or could point me in the right direction. It would be much appreciated.
/* <![CDATA[ */
/* Global variable that will contain the Google Maps object. */
var map = null
// Google Maps Demo object
var Demo = Demo || {};
// The path to your tile images.
Demo.ImagesBaseUrl = './mapImage/mapTiles/';
Demo.ImagesRoadsUrl = './mapImage/overlayRoads/';
// NuviaMap class
Demo.NuviaMap = function(container) {
// Create map
// This sets the default info for your map when it is initially loaded.
map = new google.maps.Map(container, {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeControl: false,
streetViewControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
// Set custom tiles
map.mapTypes.set('nuvia', new Demo.ImgMapType('nuvia', '#4E4E4E'));
map.setMapTypeId('nuvia');
// Loop through the marker info array and load them onto the map.
for (var key in markers) {
var markerData = markers[key];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markerData.lat, markerData.lng),
map: map,
title: markerData.title,
flat: markerData.flat,
visible: true,
infoBubble: new InfoBubble({
maxWidth: 300,
content: (markerData.image ? '<img src="' + markerData.image + '" width="80" align="left">' : '') + '<h3>' + markerData.title + '</h3>' + (markerData.info ? '<p>' + markerData.info + '</p>' : ''),
shadowStyle: 1,
padding: '10px'
}),
// You can use custom icons, default icons, etc. In my case since a city was a marker the circle icon works pretty well.
// I adjust the scale / size of the icon depending on what kind of city it is on my map.
icon: {
url: markerData.icon,
}
});
// We need to trap the click event for the marker so we can pop up an info bubble.
google.maps.event.addListener(marker, 'click', function() {
this.infoBubble.open(map, this);
});
activeMarkers.push(marker);
}
// This is dumb. We only want the markers to display at certain zoom levels so this handled that.
// Google should have a way to specify zoom levels for markers. Maybe they do but I could not find them.
google.maps.event.addListener(map, 'zoom_changed', function() {
var currentZoom = map.getZoom();
for (var i = 0; i < activeMarkers.length; i++) {
var thisTitle = activeMarkers[i].title;
if (markers[thisTitle]['zoom'][currentZoom])
activeMarkers[i].setVisible(true);
else
activeMarkers[i].setVisible(false);
}
});
// This handles the displaying of lat/lng info in the lat/lng info container defined above in the HTML.
google.maps.event.addListener(map, 'click', function(event) {
$('#latLng').html("Latitude: " + event.latLng.lat() + " " + ", longitude: " + event.latLng.lng());
});
// Listener to display the X/Y coordinates
google.maps.event.addListener(map, 'mousemove', function (event) {
displayCoord(event.latLng);
});
};
// ImgMapType class
Demo.ImgMapType = function(theme, backgroundColor) {
this.name = this._theme = theme;
this._backgroundColor = backgroundColor;
};
// Let Google know what size our tiles are and what our min/max zoom levels should be.
Demo.ImgMapType.prototype.tileSize = new google.maps.Size(256, 256);
Demo.ImgMapType.prototype.minZoom = 1;
Demo.ImgMapType.prototype.maxZoom = 5;
// Load the proper tile.
Demo.ImgMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
var tilesCount = Math.pow(2, zoom);
if (coord.x >= tilesCount || coord.x < 0 || coord.y >= tilesCount || coord.y < 0) {
var div = ownerDocument.createElement('div');
div.style.width = this.tileSize.width + 'px';
div.style.height = this.tileSize.height + 'px';
div.style.backgroundColor = this._backgroundColor;
return div;
}
var img = ownerDocument.createElement('IMG');
img.width = this.tileSize.width;
img.height = this.tileSize.height;
// This tells what tile image to load based on zoom and coord info.
img.src = Demo.Utils.GetImageUrl('tile_' + zoom + '_' + coord.x + '-' + coord.y + '.png');
return img;
};
// Just basically returns the image using the path set way above and the name of the actual image file.
Demo.Utils = Demo.Utils || {};
Demo.Utils.GetImageUrl = function(image) {
return Demo.ImagesBaseUrl + image;
};
// Opacity.
Demo.Utils.SetOpacity = function(obj, opacity /* 0 to 100 */ ) {
obj.style.opacity = opacity / 100;
obj.style.filter = 'alpha(opacity=' + opacity + ')';
};
// Create ye ol' map.
google.maps.event.addDomListener(window, 'load', function() {
var nuviaMap = new Demo.NuviaMap(document.getElementById('nuvia-map'));
});
console.log('Ready Builder');
/* ]]> */
This is the JS I am working off so far, (Credits to http://www.cartographersguild.com/showthread.php?t=21088)

Categories