openlayers5: click event position not properly set on map - javascript

I'm trying to open a popup in a map with markers, getting the markers points from a list where latitude and longitude are given, and they are plotted correctly in the map.
Following https://openlayers.org/en/latest/examples/popup.html I added the code for opening popup, and this is my code:
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
closer.onclick = function() {
overlay.setPosition(undefined);
closer.blur();
return false;
};
// create the map with the proper center
var map = new ol.Map({
controls: ol.control.defaults().extend(
[new ol.control.ScaleLine()]
),
view: new ol.View({
center: ol.proj.fromLonLat([center.long, center.lat]),
zoom: zoom
}),
overlays: [overlay],
layers: [new ol.layer.Tile(
{source: new ol.source.OSM()}
)
],
target: 'mapdiv',
keyboardEventTarget: document
}
);
// the style for the markers
var markerStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {module:ol/style/Icon~Options} */ ({
anchor: [0.5, 1],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
scale: 0.4,
src: 'img/ic_place_void_black_24dp_2x.png'
}))
});
for (i = 0; i < pointList.length; ++i) {
// add the marker
markersList[i] = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([pointList[i].long, pointList[i].lat])),
namesList: pointList[i].mediaNameList
});
// apply the style to the marker
markersList[i].setStyle(markerStyle);
}
// generate the markers vector
var markers = new ol.source.Vector({
features: markersList
});
// generate the markers layer
var markerVectorLayer = new ol.layer.Vector({
source: markers,
});
// add the markers layer to the map
map.addLayer(markerVectorLayer);
/**
* Add a click handler to the map to render the popup.
*/
map.on('singleclick', function(evt) {
var clickedPosition = ol.proj.toLonLat(evt.coordinate);
console.log(clickedPosition);;
overlay.setPosition(ol.proj.fromLonLat(clickedPosition));
});
Now I'm stuck with a unexplicable behaviour; whenever I click, the popup is shown about one screen south-east, whatever zoom level of the map.
The coordinates of clickedPosition (I'm seeing them in the console) are the correct coordinates where I clicked, but the popup is shown in a wrong point, with a shift which is always the same in pixels.
What am I missing?

You can refer overlay positioning for showing features in any world.
follow the link

Related

How to rotate markers individually in openlayers

I want to display on duty taxi positions using openlayers.
I have coordinates and heading of each taxi cab but when I'm trying to display them everything is okay with coordinates but headings aren't displaying properly. It's because I have the same style for every marker and adding them to the same vector layer.
I would like to show each vehicle with its own heading.
Any solutions for this issue will be appreciated.
My code:
var taxiMarker = new ol.style.Style({
image: new ol.style.Icon({
scale: 0.7, anchor: [0.5, 0.5],
src: 'uploads/taxiMarker.png'
})
});
var taxi_vector = new ol.layer.Vector({
source: new ol.source.Vector({
}),
style: [taxiMarker]
});
for(let i = 0; i < res.length; i++) {
let tCoords = res[i][0].split(',');
let heading = parseFloat(res[i][1]);
let marker = new ol.geom.Point(tCoords);
let featureMarker = new ol.Feature(marker);
taxiMarker.getImage().setRotation(heading);
taxi_vector.getSource().addFeature(featureMarker);
}

Javascript : get mid point (centroid) between Lat Long in Google Maps

I have a google maps based program that can calculate the area based on user input. Here the Demo JSFiddle
The HTML should be like this
<div class="google-maps" id="map" style="height: 400px; position: relative; border: 1px solid #CCC;"></div>
<p>Length (red line):
<span id="span-length">0</span> mt - Area (grey area): <span id="span-area">0</span> mt2</p>
And the Javascript
var map;
// Create a meausure object to store our markers, MVCArrays, lines and polygons
var measure = {
mvcLine: new google.maps.MVCArray(),
mvcPolygon: new google.maps.MVCArray(),
mvcMarkers: new google.maps.MVCArray(),
line: null,
polygon: null
};
// When the document is ready, create the map and handle clicks on it
jQuery(document).ready(function() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: new google.maps.LatLng(39.57592, -105.01476),
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor: "crosshair" // Make the map cursor a crosshair so the user thinks they should click something
});
google.maps.event.addListener(map, "click", function(evt) {
// When the map is clicked, pass the LatLng obect to the measureAdd function
measureAdd(evt.latLng);
});
});
function measureAdd(latLng) {
// Add a draggable marker to the map where the user clicked
var marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true,
raiseOnDrag: false,
title: "Drag me to change shape",
icon: new google.maps.MarkerImage("/images/demos/markers/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))
});
// Add this LatLng to our line and polygon MVCArrays
// Objects added to these MVCArrays automatically update the line and polygon shapes on the map
measure.mvcLine.push(latLng);
measure.mvcPolygon.push(latLng);
// Push this marker to an MVCArray
// This way later we can loop through the array and remove them when measuring is done
measure.mvcMarkers.push(marker);
// Get the index position of the LatLng we just pushed into the MVCArray
// We'll need this later to update the MVCArray if the user moves the measure vertexes
var latLngIndex = measure.mvcLine.getLength() - 1;
// When the user mouses over the measure vertex markers, change shape and color to make it obvious they can be moved
google.maps.event.addListener(marker, "mouseover", function() {
marker.setIcon(new google.maps.MarkerImage("/images/demos/markers/measure-vertex-hover.png", new google.maps.Size(15, 15), new google.maps.Point(0, 0), new google.maps.Point(8, 8)));
});
// Change back to the default marker when the user mouses out
google.maps.event.addListener(marker, "mouseout", function() {
marker.setIcon(new google.maps.MarkerImage("/images/demos/markers/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5)));
});
// When the measure vertex markers are dragged, update the geometry of the line and polygon by resetting the
// LatLng at this position
google.maps.event.addListener(marker, "drag", function(evt) {
measure.mvcLine.setAt(latLngIndex, evt.latLng);
measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
});
// When dragging has ended and there is more than one vertex, measure length, area.
google.maps.event.addListener(marker, "dragend", function() {
if (measure.mvcLine.getLength() > 1) {
measureCalc();
}
});
// If there is more than one vertex on the line
if (measure.mvcLine.getLength() > 1) {
// If the line hasn't been created yet
if (!measure.line) {
// Create the line (google.maps.Polyline)
measure.line = new google.maps.Polyline({
map: map,
clickable: false,
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 3,
path:measure. mvcLine
});
}
// If there is more than two vertexes for a polygon
if (measure.mvcPolygon.getLength() > 2) {
// If the polygon hasn't been created yet
if (!measure.polygon) {
// Create the polygon (google.maps.Polygon)
measure.polygon = new google.maps.Polygon({
clickable: false,
map: map,
fillOpacity: 0.25,
strokeOpacity: 0,
paths: measure.mvcPolygon
});
}
}
}
// If there's more than one vertex, measure length, area.
if (measure.mvcLine.getLength() > 1) {
measureCalc();
}
}
function measureCalc() {
// Use the Google Maps geometry library to measure the length of the line
var length = google.maps.geometry.spherical.computeLength(measure.line.getPath());
jQuery("#span-length").text(length.toFixed(1))
// If we have a polygon (>2 vertexes inthe mvcPolygon MVCArray)
if (measure.mvcPolygon.getLength() > 2) {
// Use the Google Maps geometry library tomeasure the area of the polygon
var area = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
jQuery("#span-area").text(area.toFixed(1));
}
}
function measureReset() {
// If we have a polygon or a line, remove them from the map and set null
if (measure.polygon) {
measure.polygon.setMap(null);
measure.polygon = null;
}
if (measure.line) {
measure.line.setMap(null);
measure.line = null
}
// Empty the mvcLine and mvcPolygon MVCArrays
measure.mvcLine.clear();
measure.mvcPolygon.clear();
// Loop through the markers MVCArray and remove each from the map, then empty it
measure.mvcMarkers.forEach(function(elem, index) {
elem.setMap(null);
});
measure.mvcMarkers.clear();
jQuery("#span-length,#span-area").text(0);
}
I'm trying get the mid point (centroid) and return the Long Lat value. It's kinda like this JSFiddle. The problem is I'm trying to get the mid point (centroid) but alywas getting an error. It's return like this :
I am appreciate if anyone can help :D
Thanks
You can declare LatLngBounds() object first, then extend your bound objects for each marker:
var bounds = new google.maps.LatLngBounds();
var loc = measure.polygon.getPath().b;
for (i = 0; i < loc.length; i++) {
bounds.extend(new google.maps.LatLng(loc[i].lat(), loc[i].lng()));
}
var marker = new google.maps.Marker({
position: bounds.getCenter(),
map: map
});
https://jsfiddle.net/xvbLr993/13/

Zoom (center) map to markers in OpenLayer3

I have problem with my OpenLayer3 map. When I add some markers to map I want to resize my map and change the zoom so that all markers were set on the screen.
My code looks like:
/** CREATE MARKERS **/
for (var i=0;i<1;i++){
var iconFeature = new ol.Feature({
geometry: new
ol.geom.Point(ol.proj.transform([Math.random()*360-180, Math.random()*180-90], 'EPSG:4326', 'EPSG:3857'))
});
vectorSource.addFeature(iconFeature);
var newBound = ol.Bounds();
newBound.extend([Math.random()*360-180, Math.random()*180-90]);
map.zoomToExtent(newBound);
}
/** MARKER STYLE **/
var iconStyle = [
new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 1,
scale: 0.07,
src: 'marker.png'
}))
})
];
/** ADD LAYER VECTOR **/
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
/** INIT MAP **/
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
}),
vectorLayer
],
overlays: [overlay],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
Is there a way to zoom the map to markers?
You have some errors in your logic and in some OL references. First you should create an ol.Extent that contains all the markers. Then use the map's view to fit it in.
// create ten random markers
for (var i = 0; i < 10; i++) {
var point = new ol.geom.Point(ol.proj.transform([Math.random() * 50, Math.random() * 50], 'EPSG:4326', 'EPSG:3857'));
var iconFeature = new ol.Feature({
geometry: point
});
vectorSource.addFeature(iconFeature);
}
// make the map's view to zoom and pan enough to display all the points
map.getView().fit(vectorSource.getExtent(), map.getSize());
Here's a plunker:
https://plnkr.co/edit/KVL14vdOSqJBxZz44s3u?p=preview
Once your vector features has been drawn you may get the extent using:
vector.on('render',function(e){
var myextent = vector.getSource().getExtent();
})
And then you may zoom to this extent using:
map.getView().fit(myextent , map.getSize());
So if you are going to use the render event
vector.on('render',function(e){
map.getView().fit(vector.getSource().getExtent(), map.getSize());
})

How to rotate feature in openlayer 3?

Need to find a way to rotate a feature in openlayer3 while editing a feature.
Like in openlayer2 https://github.com/openlayers/openlayers/blob/master/examples/rotate-features.html
function rotateFeature(feature, angle, origin) {
feature.geometry.rotate(angle, origin);
feature.layer.drawFeature(feature);
}
Basically, all you have to do is to call the rotate function for you polygon, as shown in the code below:
var vectorSource = new ol.source.Vector({});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://localhost/map_cache.php?z={z}&x={x}&y={y}'
})
}),
new ol.layer.Vector({
source: vectorSource
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var marker = new ol.geom.Polygon([[
ol.proj.transform([-16,-22], 'EPSG:4326', 'EPSG:3857'),
ol.proj.transform([-44,-55], 'EPSG:4326', 'EPSG:3857'),
ol.proj.transform([-88,75], 'EPSG:4326', 'EPSG:3857')
]]);
var featureMarker = new ol.Feature({
name: 'Marker',
geometry: marker,
});
vectorSource.addFeature(featureMarker);
//Here is the code for rotating:
marker.rotate(Math.PI / 2.0, ol.proj.transform([-16,-22], 'EPSG:4326', 'EPSG:3857'));
//////////////////////////////////////////////////
map.on('click', function(evt)
{
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
console.log(lonlat);
});
I have created an example to rotate a feature:
Gist with code
The rotate feature is built in and turned on by default. You can rotate your map by pressing alt + shift and moving your mouse on the map. A button should appear to revert back the rotation back to 0 degrees.
http://openlayers.org/en/v3.9.0/apidoc/ol.control.html

Issue with z-index of label and image using Google Maps API and MarkerWithLabel

Ever since I launched http://iknowwhereyourcatlives.com I've never been happy with the way I executed the frame around the icons. The problem is that the frame isn't on the same z-index as the icon picture so the frames overlap other photos.
To implement the frame I'm using MarkerWithLabel and a .png with a hole in it.
I've tried a number of solutions with CSS and hacks with JS to fix this but can't seem figure out why this is happening. What's interesting is that according to the Chrome console the frame is only 1 z-index above the marker image...
I'm including a code sample below which can be seen live here http://jsfiddle.net/ow3n/uwsL3os9/
// display map
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 12,
center: new google.maps.LatLng(49.47805, -123.84716),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// the image to display inside the marker
var marker_img = {
url: 'http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.8/examples/home.jpg',
size: new google.maps.Size(76, 76), // mask size
origin: new google.maps.Point(10, 10), // image anchor
anchor: new google.maps.Point(35, 88), // mask anchor
scaledSize: new google.maps.Size(95, 95) // image size
};
// marker positions
var positions = [
[49.45805, -123.84716],
[49.46805, -123.85716],
[49.47805, -123.86716]
];
// place markers on map with MarkerWithLabel
for (var i = 0; i < positions.length; i++) {
var pictureLabel = document.createElement("img");
pictureLabel.src = "http://iknowwhereyourcatlives.com/assets/img/frame.png";
var homeLatLng = new google.maps.LatLng(positions[i][0], positions[i][4]);
var marker = new MarkerWithLabel({
position: homeLatLng,
map: map,
icon: marker_img,
draggable: false,
labelContent: pictureLabel,
labelAnchor: new google.maps.Point(40, 98), // x,y
labelClass: "labels label"+i, // the CSS class for the label
labelStyle: {
opacity: 1
}
});
}

Categories

Resources