Google maps API v3: Adding polyline conflicts with multimarker - javascript

I am using Multimarker to add markers with labels to a custom google map. The div containing the label calls a function with onclick. But if I add a polyline to the map, the onclick stops working. I can not figure out why...
This is the code for adding a marker:
var fastMarkers = [];
var myLatlng = new google.maps.LatLng(70,-101);
var marker = new com.redfin.FastMarker(/*id*/1, myLatlng, ["<div onclick='test()'><span>mylabel</span></div>"], null);
fastMarkers.push(marker);
new com.redfin.FastMarkerOverlay(map, fastMarkers);
This is the polyline:
var linepathcoords = [
new google.maps.LatLng(71, -103),
new google.maps.LatLng(73, -107),
];
var linepath=new google.maps.Polyline({
path:linepathcoords,
strokeColor:"#ff0000",
strokeOpacity:0.9,
strokeWeight:2
});
//This next line is what's causing the onclick in the marker to stop working. Why?
linepath.setMap(map);
};
And this is the code for Multimarker:
/*
Copyright 2010 Redfin Corporation
Licensed under the Apache License, Version 2.0:
http://www.apache.org/licenses/LICENSE-2.0
*/
com = {redfin: {}};
/* Construct a new FastMarkerOverlay layer for a V2 map
* #constructor
* #param {google.maps.Map} map the map to which we'll add markers
* #param {Array.<com.redfin.FastMarker>} markers the array of markers to display on the map
*/
com.redfin.FastMarkerOverlay = function(map, markers) {
this.setMap(map);
this._markers = markers;
}
com.redfin.FastMarkerOverlay.prototype = new google.maps.OverlayView();
com.redfin.FastMarkerOverlay.prototype.onAdd = function() {
this._div = document.createElement("div");
var panes = this.getPanes();
panes.overlayLayer.appendChild(this._div);
}
/* Copy our data to a new FastMarkerOverlay
* #param {google.maps.Map} map the map to which the copy will add markers
* #return {FastMarkerOverlay} Copy of FastMarkerOverlay
*/
com.redfin.FastMarkerOverlay.prototype.copy = function(map) {
var markers = this._markers;
var i = markers.length;
var markersCopy = new Array(i);
while (i--) {
markersCopy[i] = markers[i].copy();
}
return new com.redfin.FastMarkerOverlay(map, markers);
};
/* Draw the FastMarkerOverlay based on the current projection and zoom level; called by Gmaps */
com.redfin.FastMarkerOverlay.prototype.draw = function() {
// if already removed, never draw
if (!this._div) return;
// Size and position the overlay. We use a southwest and northeast
// position of the overlay to peg it to the correct position and size.
// We need to retrieve the projection from this overlay to do this.
var overlayProjection = this.getProjection();
// DGF use fastloop http://ajaxian.com/archives/fast-loops-in-js
// JD Create string with all the markers
var i = this._markers.length;
var textArray = [];
while (i--) {
var marker = this._markers[i];
var divPixel = overlayProjection.fromLatLngToDivPixel(marker._latLng);
textArray.push("<div style='position:absolute; left:");
textArray.push(divPixel.x + marker._leftOffset);
textArray.push("px; top:");
textArray.push(divPixel.y + marker._topOffset);
textArray.push("px;")
if (marker._zIndex) {
textArray.push(" z-index:");
textArray.push(marker._zIndex);
textArray.push(";");
}
textArray.push("'");
if (marker._divClassName) {
textArray.push(" class='");
textArray.push(marker._divClassName);
textArray.push("'");
}
textArray.push(" id='");
textArray.push(marker._id);
textArray.push("' >");
var markerHtmlArray = marker._htmlTextArray;
var j = markerHtmlArray.length;
var currentSize = textArray.length;
while (j--) {
textArray[j + currentSize] = markerHtmlArray[j];
}
textArray.push("</div>");
}
//Insert the HTML into the overlay
this._div.innerHTML = textArray.join('');
}
/** Hide all of the markers */
com.redfin.FastMarkerOverlay.prototype.hide = function() {
if (!this._div) return;
this._div.style.display = "none";
}
/** Show all of the markers after hiding them */
com.redfin.FastMarkerOverlay.prototype.unhide = function() {
if (!this._div) return;
this._div.style.display = "block";
}
/** Remove the overlay from the map; never use the overlay again after calling this function */
com.redfin.FastMarkerOverlay.prototype.onRemove = function() {
this._div.parentNode.removeChild(this._div);
this._div = null;
}
/** Create a single marker for use in FastMarkerOverlay
* #constructor
* #param {string} id DOM node ID of the div that will contain the marker
* #param {google.maps.LatLng} latLng geographical location of the marker
* #param {Array.<string>} htmlTextArray an array of strings which we'll join together to form the HTML of your marker
* #param {string=} divClassName the CSS class of the div that will contain the marker. (optional)
* #param {string=} zIndex zIndex of the div that will contain the marker. (optional, 'auto' by default)
* #param {number=} leftOffset the offset in pixels by which we'll horizontally adjust the marker position (optional)
* #param {number=} topOffset the offset in pixels by which we'll vertically adjust the marker position (optional)
*/
com.redfin.FastMarker = function(id, latLng, htmlTextArray, divClassName, zIndex, leftOffset, topOffset) {
this._id = id;
this._latLng = latLng;
this._htmlTextArray = htmlTextArray;
this._divClassName = divClassName;
this._zIndex = zIndex;
this._leftOffset = leftOffset || 0;
this._topOffset = topOffset || 0;
}
/** Copy the FastMarker
* #return {com.redfin.FastMarker} duplicate of this marker
*/
com.redfin.FastMarker.prototype.copy = function() {
var htmlArray = this._htmlTextArray;
var i = htmlArray.length;
var htmlArrayCopy = new Array(i);
while (i--) {
htmlArrayCopy[i] = htmlArray[i];
}
return new com.redfin.FastMarker(this._id, latLng, htmlArrayCopy, this._divClassName, this._zIndex, this._leftOffset, this._topOffset);
}
Additional info: Before adding the polyline I can use the "inspect" tool in Firefox and select the div and span containing the label. But after adding the polyline the div is gone (the label is still visible on the map, but I can not click it, and I can not select it with the inspect-tool. Also, after adding the polyline I see in the Firefox "inspect"-list that a lot of divs suddenly have "overflow:hidden" on them, and I don't think they had it before. Is this a clue? Also it does not help if I remove the polyline. The onclick function of the labels still don't work. Like, I can add polyline, remove it, add labels, and the labels' onclick is not working. Or I can add labels, add ployline, labels' onclick stops working, remove polyline, labels' onclick still not working.)

There are differences between the Multimarker js-script contained in the zip-file offered for download (2013-03-22) (
http://code.google.com/p/multimarker/) and the js-script accessed through http://multimarker.googlecode.com/svn/trunk/fast-marker-overlay/maps-v3/src/FastMarkerOverlay.js.
The script accessed through http:// says:
line 24:
panes.floatPane.appendChild(this._div);
instead of
panes.overlayLayer.appendChild(this._div);
and line 140:
this.latLng
instead of
latLng
I changed these things in the downloaded script and now it works! Thank you so much geocodezip for helping me solve this! If there is any way I can give you cred for this please tell me. I'm new to the site and I'm not sure of how it works...

Related

Here Maps polyline with altitude

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.

mapbox marker rotation/bearing

is there any chance to set the rotation for a marker? For now, I set the map bearing to the angle of one marker, but the others should have their own marker bearing.
At the moment, I'm using the marker definition like so:
var marker_el = document.createElement('div');
marker_el .className = 'marker';
var new_marker = new mapboxgl.Marker(marker_el)
.setPopup(marker_PopUp);
and set it to the map:
new_marker.setLngLat([lon, lat]);
new_marker.addTo(map);
I'm using JS and react and for the map mapbox-gl
so because there are no answers, I self answer my post with a working solution for me:
var angle = "yourAngle";
var rotateString = "rotate(" + angle + "deg)";
var marker_el = document.createElement('div');
marker_el.className = 'marker';
var new_marker = new mapboxgl.Marker(marker_el);
new_marker.addTo(map);
/* important here is to append the rotate property because the transform
property is already being updated */
marker_el.style.transform = marker_el.style.transform + rotateString;

How to drawing in Here Map with HERE MAP Javascript 3 API?

How to drawing a geoshapes (polygon) in HERE Maps javascript 3.0 with mouse event click? and save the coordinates in database..
I search the guides at developer.here.com but no one script guides showing how to draw in here map javascript 3.0 API. (https://developer.here.com/api-explorer/maps-js/geoshapes/polygon-on-the-map)
Beside that in javascript 2.5 API show the guides, but it will be expired and deleted soon.
here a script to draw in javascript 2.5 (http://developer.here.com/apiexplorer/index.html#js/pub/shapes/map-with-polyline-on-click/):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
<base href="./../../../..//examples/public/api-for-js/shapes/map-with-polyline-on-click.html" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>HERE Maps API for JavaScript Example: Click to create a polyline on map</title>
<meta name="description" content="Creating a polyline wih markers by clicking on the map"/>
<meta name="keywords" content="drawpolyline, map objects, shape, shapes, triangle, rectangle, circle, polyline, polygon"/>
<meta name=viewport content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" type="text/css" href="./../../../..//examples/templates/js/exampleHelpers.css"/>
<script type="text/javascript" charset="UTF-8" src="http://js.cit.api.here.com/se/2.5.4/jsl.js?with=all"></script>
<script type="text/javascript" charset="UTF-8" src="./../../../..//examples/templates/js/exampleHelpers.js"></script>
<style type="text/css">
html {
overflow:hidden;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
#mapContainer {
width: 100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
</style>
</head>
<body>
<div id="mapContainer"></div>
<div id="uiContainer"></div>
<script type="text/javascript" id="exampleJsSource">
nokia.Settings.set("app_id", "DemoAppId01082013GAL");
nokia.Settings.set("app_code", "AJKnXv84fjrb0KIHawS0Tg");
// Use staging environment (remove the line for production environment)
nokia.Settings.set("serviceMode", "cit");
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 10,
components: [
// ZoomBar provides a UI to zoom the map in & out
new nokia.maps.map.component.ZoomBar(),
// we add the behavior component to allow panning / zooming of the map
new nokia.maps.map.component.Behavior(),
// creates UI to easily switch between street map satellite and terrain mapview modes
new nokia.maps.map.component.TypeSelector()
]
});
var noteContainer = new NoteContainer({
id: "drawPolylineUi",
parent: document.getElementById("uiContainer"),
title: "Drawing a polyline",
content:
'<p>Click or touch anywhere on the map to add a new point to the existing polyline.</p>' +
'<input id="resetPolyline" role="button" type="button" value="Reset Polyline"/>'
});
// We bind DOM element to variable so we use it later to install event handler.
var resetPolylineUiElt = document.getElementById("resetPolyline");
// Javascript inheritance helper function
function extend(B, A) {
function I() {}
I.prototype = A.prototype;
B.prototype = new I();
B.prototype.constructor = B;
}
var MarkerPolyline = function (coords, props) {
// Call the "super" constructor to initialize properties inherited from Container
nokia.maps.map.Container.call(this);
// Calling MarkerPolyline constructor
this.init(coords, props);
};
extend(MarkerPolyline, nokia.maps.map.Container);
// MarkerPolyline constructor function
MarkerPolyline.prototype.init = function (coords, props) {
var i,
coord,
marker,
lineProps = props.polyline || {},
markerProps = (this.markerProps = props.marker || {});
this.coords = {};
// Create a polyline
this.polyline = new nokia.maps.map.Polyline(coords, lineProps);
// Add the polyline to the container
this.objects.add(this.polyline);
/* We loop through the point to create markers
* for each of the points and we store them
*/
for (i = 0; coord = coords[i]; i++) {
marker = new nokia.maps.map.StandardMarker(coord, markerProps);
this.coords[coord.latitude + "_" + coord.longitude] = { idx: i + 1, marker: marker };
this.objects.add(marker);
}
};
// The add function allows you to add a new point to a MarkerPolyline
MarkerPolyline.prototype.add = function (coord) {
// Create a new standard marker
var markerProps = this.markerProps,
marker,
key = coord.latitude + "_" + coord.longitude;
if (!this.coords[key]) {
marker = new nokia.maps.map.StandardMarker(coord, markerProps);
this.coords[key] = { idx: this.objects.getLength(), marker: marker };
/* Add the marker to the object's collections
* so the marker will be rendered onto the map
*/
this.objects.add(marker);
this.polyline.path.add(coord);
}
};
// The remove function allows you to remove a point from MarkerPolyline
MarkerPolyline.prototype.remove = function (coord) {
var coords = this.polyline.path.internalArray,
i = this.polyline.path.getLength(),
marker,
key = coord.latitude + "_" + coord.longitude,
idx;
if (!this.coords[key])
return;
while (i--) {
if (coords[i * 3 ] === coord.latitude && coords[i * 3 + 1] === coord.longitude) {
idx = i;
}
}
// Index of coordinate found, now we remove coordinate from polyline
this.polyline.path.remove(idx);
// Remove the marker
marker = this.coords[key].marker;
this.objects.remove(marker);
marker.destroy();
delete this.coords[key];
};
// Set of initial geo coordinates to create the polyline
var coords = [
new nokia.maps.geo.Coordinate(52.5032, 13.2790),
new nokia.maps.geo.Coordinate(52.5102, 13.2818),
new nokia.maps.geo.Coordinate(52.5121, 13.3224),
new nokia.maps.geo.Coordinate(52.5145, 13.3487),
new nokia.maps.geo.Coordinate(52.5139, 13.3501),
new nokia.maps.geo.Coordinate(52.5146, 13.3515),
new nokia.maps.geo.Coordinate(52.5161, 13.3769)
];
// Create a new polyline with markers
var markerPolyline = new MarkerPolyline(
coords,
{
polyline: { pen: { strokeColor: "#00F8", lineWidth: 4 } },
marker: { brush: { color: "#1080dd" } }
}
);
/* Add the markerPolyline to the map's object collection so
* all of its containing shapes will be rendered onto the map.
*/
map.objects.add(markerPolyline);
/* We would like to add event listener on mouse click or finger tap so we check
* nokia.maps.dom.Page.browser.touch which indicates whether the used browser has a touch interface.
*/
var TOUCH = nokia.maps.dom.Page.browser.touch,
CLICK = TOUCH ? "tap" : "click",
addedCoords = [];
// Attach an event listeners on mouse click / touch to add points to
map.addListener(CLICK, function (evt) {
// We translate a screen pixel into geo coordinate (latitude, longitude)
var coord = map.pixelToGeo(evt.displayX, evt.displayY);
// Next we add the geoCoordinate to the markerPolyline
markerPolyline.add(coord);
// We store added coordinates so we can remove them later on
addedCoords.push(coord);
});
// Reset markerPolyline to its original shape on click of reset button
resetPolylineUiElt.onclick = function () {
var i = addedCoords.length;
while (i--) {
markerPolyline.remove(addedCoords[i]);
}
addedCoords = [];
};
// Zoom the map to encapsulate the initial polyline, once the map is initialized and ready
map.addListener("displayready", function () {
map.zoomTo(markerPolyline.getBoundingBox());
});
</script>
</body>
</html>
You must update the strip of the GeoShape:
get the strip via getStrip()
push a geo.Point to the strip via pushPoint()
apply the updated strip via setStrip()
// enable the event system
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map)),
//create the line
line=new H.map.Polyline(new H.geo.Strip([ 52.5032, 13.2790,0,
52.5102, 13.2818,0,
52.5121, 13.3224,0,
52.5145, 13.3487,0,
52.5139, 13.3501,0,
52.5146, 13.3515,0,
52.5161, 13.3769,0])
);
//draw the line
map.addObject(line);
//add tap-listener
map.addEventListener('tap', function(e){
var pointer = e.currentPointer,
//create geo.Point
latLng = map.screenToGeo(pointer.viewportX, pointer.viewportY),
//get current strip
strip=line.getStrip();
//push point to strip
strip.pushPoint(latLng);
//set updated strip
line.setStrip(strip);
});

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.......

How to add text on circle and how to combine circle when zoom out different cicle

I have more than 1000 markers at 3 different location in my Map.
I read Lat and Long from a text file and render it in Google maps and create circle over them on the basis of country name. And count the number of markers in those circle.
Now what i am not able to do is?
(1) I have to print the text of count on those circle (How to do without using Cluster ?)
(2) When i zoom out circle overlaps . So whenever circle overlaps it should combine the 2 radius of these two circles and should make one big circle covering the markers of the two smaller (smaller 2 will now disappear resulting on total of marker on the bigger one only).
My full code to do this (http://prntscr.com/6kt30w) is :
$.ajax({
type: 'GET',
url: './App_Start/TextFile/latLongList3.txt',
dataType: 'text',
}).success(function (data)
{
var s2 = data.replace(/^.*$/, " ").replace(/\r\n/g, " ");
var array = s2.split(/[ ]+/g);
var test = [].concat.apply([], array.map(function (array) { return array.split(/\s+/); }))
var col1 = [];
var col2 = [];
var col3 = [];
var j = 0;
for (var i = 0; i <= test.length - 3; i = i + 3)
{
col1[j] = test[i];
col2[j] = test[i + 1];
col3[j] = test[i + 2];
var myLatlng = new google.maps.LatLng(col3[j], col2[j]);
marker = new google.maps.Marker(
{
position: myLatlng,
map: map,
title: 'Hello World! ' + col1[j]
});
markers.push(marker);
if (j > 0) {
LatLong[j] = myLatlng;
}
j++;
}
})
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I don't want to use MarkerClusterer because it is very small. Yes it's true that it will do the 2 tasks i want to accomplish but the problem i feel with it is when i have markers all over the country then MarkerClusterer just hovers over a very little part of the country whereas i want the circle to hover over all country wherever i have marker and it should have text on it. So if there is any alternative to make the size of cluster such that it cover all the markers in the entire country(because my 1 country is full of markers) and has text on it than any way to do this is welcomed too.
Could some one please help me in solving the 2 problems ?
I have to print the text of count on those circle (How to do without
using Cluster ?)
You can use the following to get count of marker from marker.length
var markers = [];
for (var i = 0; i < 100; i++) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var marker = new google.maps.Marker({'position': latLng});
markers.push(marker);
}
To add the count to circle, you can look at this JSFiddel.
I still have to look more your second problem
Finally i found the solution of it.I simply used MarkerClusterer and got it done by increasing its size.
And it works perfectly for me.

Categories