Move OpenLayers.Popup up to 10 pixel and left 15 pixel? - javascript

Good afternoon, I have a popup that is in the map and I want only move 10 pixels high and 15 pixels to the left, the problem is that when you change its position in latitude and longitude, is in another position completely and when I zoom away from the marker, what I want is just to move to the new position regardless of the zoom, always remains above the marker.
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('/openlayers/img/marker.png',size,offset);
var lonlat = new OpenLayers.LonLat(long,lat);
var proj_1 = new OpenLayers.Projection("EPSG:4326");
var proj_2 = new OpenLayers.Projection("EPSG:900913");
var EPSG = lonlat.transform(proj_1,proj_2);
var marker = new OpenLayers.Marker(EPSG, icon);
markers.addMarker(marker);
marker.events.register("click", marker, function(e){ // on click popup
var popup = new OpenLayers.Popup.FramedCloud(id,
marker.lonlat,
new OpenLayers.Size(200,200),
'<div class="popup">info example</div>',
null,true);
map.addPopup(popup);
});
var labelepopup = new OpenLayers.Popup(null,
EPSG,
new OpenLayers.Size(37,13),
'<p style="font-size: 8.5px;">always info</p>'
);
map.addPopup(labelepopup);
The popup on the marker as labelepopup appear, all I want is to accommodate the labelepopup above the marker.

You can use getPixelFromLonLat map function to get the exact pixel from a latitude and a longitude and then use the Pixel object returned to add or remove the desired pixels. Then you can change popup position using moveTo popup function that requires a Pixel object.
Something like this:
var pixel = map.getPixelFromLonLat(popup.lonlat); //or use another OpenLayers.LonLat object
pixel.x += DESIRED_X_AMOUNT;
pixel.y += DESIRED_Y_AMOUNT;
popup.moveTo(pixel);

Related

JavaScript Polymaps library: Get mouse coordinates

I use the polymaps library to display a custom tiled map. Whenever the user clicks on it, I need to know the coordinates of that point. Not the lat/lon values that map.mouse(e) gives, but pixel coordinates.
var po = org.polymaps;
var div = document.getElementById("map");
var map = po.map()
.container(div.appendChild(po.svg("svg")))
.zoomRange([0,8])
.zoom(1)
.add(po.image()
.url(getTile));
map.add(po.interact())
.add(po.hash());
$(div).mousemove(function(e) {
???
})
Does this library provide a function to do this?
To obtain the mouse position on the original image from which the tilemap was created, use the following code:
$(div).mousemove(function(e) {
// Get column, row and zoom level of mouse position
var crz = map.locationCoordinate(map.pointLocation(map.mouse(e)));
// Normalize the column and row values to the 0..1 range
var zoomMultiplier = Math.pow(2, crz.zoom-1);
var x01 = crz.column/zoomMultiplier;
var y01 = crz.row/zoomMultiplier;
// Multiply with the original image width and height
var originalWidth = 32768;
var originalHeight = 32768;
var mx = x01*originalWidth;
var my = y01*originalHeight;
// Now we have the mouse coordinates on the original image!
console.log(mx, my);
})

Take snapshot of a specific area under google map javascript

I am trying to take the snapshot of an area enclosed by a rectangle drawn on the google map. Is it possible to take the snapshot of the area beneath the rectangle? I have searched for answers but couldn't find any helpful info.
Rectangle drawn on the map
I tried to take the snapshot of the area under rectangle using static map API by specifying the map centre, zoom level, image width and image height. Like
https://maps.googleapis.com/maps/api/staticmap?center=CENTER OF THE RECTANGLE&zoom=ZOOM LEVEL OF THE MAP&size=WIDTH AND HEIGHT OF THE RECTANGLE&maptype=satellite&key=API KEY
Here is the code I tried,
var zoom = map.zoom;
var centre = rectangle.getBounds().getCenter(); //rectangle is the shape drawn on the map
var spherical = google.maps.geometry.spherical;
bounds = rectangle.getBounds(); //rectangle is the shape drawn on the map
cor1 = bounds.getNorthEast();
cor2 = bounds.getSouthWest();
cor3 = new google.maps.LatLng(cor2.lat(), cor1.lng());
cor4 = new google.maps.LatLng(cor1.lat(), cor2.lng());
width = spherical.computeDistanceBetween(cor1,cor3);
height = spherical.computeDistanceBetween( cor1, cor4);
Now I downloaded the image using this URL,
"https://maps.googleapis.com/maps/api/staticmap?center=" + centre.lat() + "," + centre.lng() + "&zoom=" + zoom + "&size=" + width + "x" + height + "&maptype=satellite&key=API_KEY"
Original URL : "https://maps.googleapis.com/maps/api/staticmap?center=40.804197008355914,-74.11213619168848&zoom=20&size=26x37&maptype=satellite&key=API_KEY"
Output image I got
My expected output
I got the image, but the image doesn't include the whole area enclosed by the rectangle(It is too small). what I am doing wrong? Is there any other methods to do it?
The main mistake that you have in your code is that the width and height parameters of Static Maps API must be in pixels. Currently you calculate a distance in meters and pass it in Static Maps URLs instead of pixels.
I created an example based on your sample code and was able to create a correct static maps URL. Please have a look at my example. The distanceInPx function is the most important thing. Create the rectangle with drawing manager and click the Show static map link. Also, note that Static Maps API are limited to 640x640 px image size in Standard plan, so you cannot create a link for rectangles that have a bigger size.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 28.45765, lng: -16.363564},
zoom: 21,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['rectangle']
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, "rectanglecomplete", function(rectangle){
function distanceInPx(pos1, pos2) {
var p1 = map.getProjection().fromLatLngToPoint(pos1);
var p2 = map.getProjection().fromLatLngToPoint(pos2);
var pixelSize = Math.pow(2, -map.getZoom());
var d = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y))/pixelSize;
return Math.round(d);
}
var zoom = map.zoom;
var centre = rectangle.getBounds().getCenter(); //rectangle is the shape drawn on the map
var spherical = google.maps.geometry.spherical;
bounds = rectangle.getBounds(); //rectangle is the shape drawn on the map
var cor1 = bounds.getNorthEast();
var cor2 = bounds.getSouthWest();
var cor3 = new google.maps.LatLng(cor2.lat(), cor1.lng());
var cor4 = new google.maps.LatLng(cor1.lat(), cor2.lng());
var width = distanceInPx(cor1, cor4);
var height = distanceInPx(cor1, cor3);
var imgUrl = "https://maps.googleapis.com/maps/api/staticmap?center=" +
centre.lat() + "," + centre.lng() + "&zoom=" + zoom +
"&size=" + width + "x" + height + "&maptype=satellite&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU";
var aElem = document.getElementById("staticLink");
aElem.setAttribute("href", imgUrl);
aElem.style.display="block";
});
}
#map {
height: 100%;
}
html, body {
height: 95%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<a id="staticLink" href="#" target="_blank" title="Show static map" style="display:none;">Show static map</a>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=drawing&callback=initMap"
async defer></script>
This example is also available at jsbin: http://jsbin.com/humuko/edit?html,output
I hope this helps!

Drawing line (freeform) on Google maps?

Hi I want to draw a line (free-form, Photoshop pencil / paintbrush style) over Google maps.
What would be the best way to do it?
How complicated would it be to do this AND keep the zoom option (so that line scales / disappears when the map is scaled)?
Which would be the best library to use for that (canvas? svg? something else)?
You could use the built indrawing tools, but if I recall correctly, you would need to click quite a bit to get a free form line.
Here's another pretty rough idea. Capture the mouse coordinates of the map container, grab the latLng from a google.maps.MapCanvasProjection and push the coordinates to a polyline path.
var map;
var elevator;
var myOptions = {
zoom: 6,
center: new google.maps.LatLng(46.87916, -3.32910),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map')[0], myOptions);
var markers = [];
var isDrawing = false;
var overlay = new google.maps.OverlayView();
overlay.draw = function () {};
overlay.setMap(map);
// Add a listener for idle event and call getElevation on a random set of marker in the bound
google.maps.event.addListener(map, 'click', function () {
var polyLine = new google.maps.Polyline({
map: map
});
$("#map").mousemove(function (e) {
var pageX = e.pageX;
var pageY = e.pageY;
var point = new google.maps.Point(parseInt(pageX), parseInt(pageY));
var latLng = overlay.getProjection().fromDivPixelToLatLng(point);
polyLine.getPath().push(latLng);
});
});

how to add marker on screen touch with openlayers

i'm using sencha touch and openlayers for a mobile app !
i want to add a marker when i touch the map like "onLongPress" with android !
what m searching for is a similar code but who support the touch screen .
map.events.register("click", map, function(e) {
//var position = this.events.getMousePosition(e);
var position = map.getLonLatFromPixel(e.xy);
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('images/mark.png', size, offset);
var markerslayer = map.getLayer('Markers');
markerslayer.addMarker(new OpenLayers.Marker(position,icon));
});
thank you :)

Get Markers Coordinates To MAP

Im try to get the markers coordinates to the map, or to the window, to set a special functions when i make over with the mouse, my test code is this:
var multiMarker = [];
var xmyOptions = { // Ponemos unas coordenadas iniciales al mapa de google maps.
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var xmap = new google.maps.Map($('#map_canvas2').get(0), xmyOptions); // Iniciamos el mapa indicando el Div donde se va a cargar y las opciones.
for (x=0; x<9; x++) {
multiMarker[x] = new google.maps.Marker({ // Definimos una nueva "marca" o puntero
position: new google.maps.LatLng('40.' + Math.floor(Math.random()*99999999), '-3.' + Math.floor(Math.random()*99999999)),
draggable: true,
map: xmap,
title: 'Ejemplo marcador arrastrable'
});
google.maps.event.addListener(multiMarker[x], 'mouseover', function(){
console.log(this);
});
}
var bounds = new google.maps.LatLngBounds();
for (index in multiMarker) {
var data = multiMarker[index];
bounds.extend(new google.maps.LatLng(data.position.Oa, data.position.Pa));
}
xmap.fitBounds(bounds);
The problem is i cant get this coordinates in the marker[x] object, i only see the latitude and longitude, and I need the top, left, bottom or right position of the marker to set special floating tooltips. The API doesnt have this info?
Thanks.
I answered similar question here: How to access Google Maps API v3 marker's DIV and its pixel position?
What you can get is position of marker in world coordinate, then convert to offset from top left corner of visible rectangle. But it's only position, you don't have access to marker itself, so you can't add events to it or alter marker div this way.
var scale = Math.pow(2, map.getZoom());
var nw = new google.maps.LatLng(
map.getBounds().getNorthEast().lat(),
map.getBounds().getSouthWest().lng()
);
var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition());
var pixelOffset = new google.maps.Point(
Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
);
If for some reason you need access to marker's div, then you need to check what divs are created for map, select in which layer (markers are in one layer, but I don't remember which, don't confuse them with marker shadows :-)) and then somehow check which position this divs have, to select one you need.

Categories

Resources