get mouse postion returns wrong xy - javascript

I have an Open-layers map, and I want to add a marker with a mouse over event that displays a pop up. my code is doing this however the pop-up is displayed not on top of the icon that is "mouse overed".
Instead the popup is displayed at the far side of the screen and moves the map slightly. I have added a mouse move function that tell me where the cursor is on the screen and the mouse move event is giving the correct coordinates but the mouseover is giving me values that are almost zero.
I am very new to JavaScript and I completely lost as to what I have got wrong here. any help would be greatly appreciated
here is the javascript
map = new OpenLayers.Map("map");
//var layer= new OpenLayers.Layer.OSM();
layer = new OpenLayers.Layer.Google(
"Google Hybrid",
{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20});
layer.wrapDateLine=false;
map.addLayer(layer);
map.zoomTo(3);
var clat=45.003585;
var clon=6.120495;
var lonlat = new OpenLayers.LonLat(clon,clat).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
map.setCenter(lonlat,18);
markers = new OpenLayers.Layer.Markers("Cities");
map.addLayer(markers);
var location = new OpenLayers.LonLat(6.12053255092622,45.00374430489748).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
marker=new OpenLayers.Marker(location,icon.clone());
map.addControl(
new OpenLayers.Control.MousePosition(
{
prefix: '<a target="_blank" ' +
'href="http://spatialreference.org/ref/epsg/4326/">' +
'EPSG:4326</a> coordinates: ',
separator: ' | ',
numDigits: 2,
emptyString: 'Mouse is not over map.'
})
);
map.events.register("mousemove", map, function(e)
{
position = this.events.getMousePosition(e);
OpenLayers.Util.getElement("coords").innerHTML = position;
lonlat = map.getLonLatFromPixel(position).transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
OpenLayers.Util.getElement("coords_gps").innerHTML = "lat= " +lonlat.lat +" long= "+lonlat.lon;
});
//here add mouseover event
marker.events.register('mouseover', marker, function(ev) {
lonlat = map.getLonLatFromPixel(this.events.getMousePosition(ev));
console.log(this.events.getMousePosition(ev));//.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326")));
popup = new OpenLayers.Popup.FramedCloud("Popup",
lonlat,
null,
'<div>Hello World! Put your html here</div>',
null,
false);
map.addPopup(popup);
});
//here add mouseout event
marker.events.register('mouseout', marker, function(evt) {popup.hide();});
markers.addMarker(marker);
map.events.register("click",map, function (e){
// alert("here");
position = this.events.getMousePosition(e);
lonlat = map.getLonLatFromPixel(position).transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
$('#lat').val(lonlat.lat);
$('#lon').val(lonlat.lon);
});

Related

Adding html text to a H.map.DomMarker

I want to add text to a marker. I have a variable with an attribute "text" that I want to appear in the Marker, when it appears on the map.
var baseLat = baseLocation.lat;
var baseLng = baseLocation.lng;
var basePoint = new H.geo.IPoint( baseLat , baseLng );
var baseMarker = new H.map.DomMarker( basePoint );
var markerHTML = '<div class="px_marker">' + baseLocation.text + '</div>';
baseMarker.setZIndex(1);
baseMarker.setData(markerHTML);
domGroup.addObject(baseMarker);
baseLocation.text = "test"
I would expect a marker with the word "test"
While creating map object, you can specify the coordinates and icon both as parameters, and in icon, you can embed both the text and animation, if is required.
please refer following example which illustrates the same requirement
developer.here.com/api-explorer/maps-js/v3.0/markers/map-with-dom-marker
Also a little code snippnet that could help..happy coding..!!
<html>
<script>
// Initialize the platform object:
var platform = new H.service.Platform({
'app_id': ‘xxxxxxxxxx’,
'app_code': ‘yyyyyyyyyyy’
});
// Obtain the default map types from the platform object
var maptypes = platform.createDefaultLayers();
// Instantiate (and display) a map object:
var map = new H.Map(
document.getElementById('mapContainer'),
maptypes.normal.map,
{
zoom: 10,
center: { lng: 13.4, lat: 52.51 }
});
// Define a variable holding SVG mark-up that defines an animated icon image:
var markerHTML = '<div>' + "text" + '</div>';
// Create an icon object, an object with geographic coordinates and a marker:
var icon = new H.map.DomIcon(markerHTML),
coords = {lat: -22.8906, lng: -43.2283},
baseMarker = new H.map.DomMarker(coords, {icon: icon});
// Set map center and zoom, add the marker to the map:
map.setCenter(coords);
map.setZoom(18);
map.addObject(baseMarker);
</script>
</html>

Trailing route polyline on marker move event

I am using leaflet and pubnub libraries to move marker smoothly on Google maps, with real-time data. This functionality is working fine and marker moves smoothly on map from one point to next point.
But I could not find a way to draw a route polyline from marker to destination and trailing line with marker move event. I want to show route line same as Uber, from car icon to destination and trailing line with car movement.
Any help would be appreciated.
I am using the following pubnub SDK:
https://www.pubnub.com/developers/eon/map/bus/
Here is my pubnub object initialization code:
var connectline = 0;
var lastlng = [40.80523269999999, -73.7412536];
var pubnub = new PubNub({
publishKey: 'pub-c-5e4c8233-c59b-448c-a809-9c09f61715XX',
subscribeKey: 'sub-c-74a7e51a-ad14-11e4-a808-02ee2ddab7XX'
});
var trip = '134386886'; // '134386875';
var channel = 'TRIP_' + trip;
alert("channel name=" + channel);
var map = eon.map({
pubnub: pubnub,
id: 'map',
options: {
center: new L.LatLng(40.80523269999999, -73.7412536),
zoom: 15
},
mbId: 'ianjennings.l896mh2e',
mbToken: 'pk.eyJ1IjoiaWFuamVubmluZ3MiLCJhIjoiZExwb0p5WSJ9.XLi48h-NOyJOCJuu1-h-Jg',
channels:[channel],
message: function (data) {
map.setView(data[trip].latlng, 15);
},
transform: function(m) {
var a = {};
a[m.common.trip_id] = {
latlng: [m.common.latitude, m.common.longitude],
data: m.common
}
return a;
},
rotate: true,
// history: true,
marker: function (latlng, data) {
var icon = new Icon();
var parisKievLL = [lastlng, latlng];
var marker = L.Marker.movingMarker(parisKievLL, [10000], {icon:icon}).addTo(map);
lastlng = latlng;
// alert('marker data=' + JSON.stringify(data));
// alert('market latlng' + JSON.stringify(latlng));
// var latlng = [data.latitude, data.longitude];
var addressMarker = L.marker([40.80523269999999, -73.7412536]).addTo(map);
marker.bindPopup('car #:' + data.device_id);
return marker;
}
});

Add event listeners to several map markers

I have the following function to set the Markers.
function setMarkers(map, locations, contenido) {
// Add markers to the map
console.log(contenido);
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var image = {
url: '<?php echo Yii::$app->request->baseUrl."/images/pinrojo.png";?>',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(20, 32),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 32)
};
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var objeto_contentString = {};
var objeto_infowindow = {};
var object_marker = {};
for (var i = 0; i < locations.length; i++) {
objeto_contentString['contentString' + i ] = contenido[i]["META"] + "<BR/>" + contenido[i]["VENTA"];
objeto_infowindow['infowindow' + i] = new google.maps.InfoWindow({
content: objeto_contentString['contentString' + i ]
});
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
object_marker['marker' + i] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
google.maps.event.addListener(object_marker['marker' + i], 'click', function() {
objeto_infowindow['infowindow' + i].open(map,object_marker['marker' + i]);
});
}
console.log(objeto_contentString);
}
I would like to know how to add an event listener to every marker, but how? Is there a way to dynamically add those element listeners? I heard about some closure, but not sure how to implement them. With the current code, it will add only a listener to the last element of the array in the loop.
GoogleMap allows you to add event listeners to multiple markers. However, your code above won't work due to the fact that you are reusing the marker variable for all different markers. What you should be doing is, assign a marker variable for each of your objects. Don't reuse object_marker for all items.
// var object_marker = {}; // DONT USE IT
var markerCollections = [];
var objeto_infowindow = [];
for (var i = 0; i < locations.length; i++) {
objeto_contentString['contentString' + i ] = contenido[i]["META"] + "<BR/>" + contenido[i]["VENTA"];
objeto_infowindow['infowindow' + i] = new google.maps.InfoWindow({
content: objeto_contentString['contentString' + i ]
});
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
// One object marker per one entity
var object_marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
var onclick = function(objeto_infowindow,marker){
var obj = objeto_infowindow;
return function(){
obj.open(map,marker);
}
}
google.maps.event.addListener(object_marker, 'click', onclick(objeto_infowindow['infowindow' + i], object_marker) );
// Keep the marker for later clean up if required
markerCollections.push(object_marker);
}
Instead of marker object, create markerArray to keep track of markers.
var markerArray=[];
Then use for loop to add all markers in the array.
Then finally use another for loop to iterate through markerArray to add all the listeners:
for(var i=0;i<markerArray.length;i++){
markerArray[i].on("click",function(){...});
}

Getting " NULL / Empty " values for input Text if the page remains idle in some time?

Getting " NULL / Empty " values for couple of times (I have typed values) in a input textbox due to idleness of web page(idleness might be the reason, Itz my Guess).
I can give names for multiple shapes by one by one. But If i have hold the webpage for 5 mins. Then I could not give a name and description for the polygon (in the infowindow object) at the first time. At the second time I can give a name for InfoWindow Object.But it is not getting close automatically. I have to manually close it out. Please help me to write a error less code with Google Maps API.
Things I have done. Giving a Name and Description for each Polygon after the polygon has been drawn by the help of infoWindow Object. The code is below. Help me to find the error in my code and help me to identify the area of my poor implementation.
google.maps.visualRefresh = true;
var polygons = [];
var polygonShape = [];
var polygonJson = {};
var map;
var drawingTool = new google.maps.drawing.DrawingManager();
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom : 4,
center : new google.maps.LatLng(37.5499, -95.5524),
mapTypeId : google.maps.MapTypeId.ROADMAP
});
drawingTool.setOptions({
drawingMode : google.maps.drawing.OverlayType.POLYGON,
drawingControl : true,
drawingControlOptions : {
position : google.maps.ControlPosition.TOP_CENTER,
drawingModes : [ google.maps.drawing.OverlayType.POLYGON ]
}
});
drawingTool.setMap(map);
google.maps.event.addListener(drawingTool, 'overlaycomplete', function(event) {
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
createPolygon(event.overlay);
}
});
}
function createPolygon(polygon) {
polygons.push(polygon);
this.vertices = polygon.getPath();
var content = '<label><b>Region Name : </b></label><input type="text" size="20" id="region_name"/></br><label align="top"><b>Description : </b></label><textarea id="region_desc" cols="20" rows="3"></textarea><br/><input type="button" value="Save Region" onclick="get_point_info(vertices);"/><br/>'
+ '<b>-----INFO-----</b>';
verticesLoop(this.vertices, content);
}
function get_point_info(vertices) {
var vertice = vertices;
var RegionName = document.getElementById('region_name').value;
var RegionDesc = document.getElementById('region_desc').value;
this.infoWindow.close();
polygonJson = {
data : vertice,
regionName : RegionName,
regionDescription : RegionDesc
};
alert(Object.toJSON(polygonJson));
}
function verticesLoop(vertices, content) {
var clat = 0;
var clng = 0;
var contents = content;
var vert = vertices;
vert.forEach(function(xy, i) {
var contentString = '<br/><b>Lat :</b> ' + xy.lat() + '<b>Long : </b>'
+ xy.lng();
contents = contents + contentString;
clat = xy.lat();
clng = xy.lng();
});
displayInfo(contents, new google.maps.LatLng(clat, clng));
}
function displayInfo(conString, customPosition) {
this.infoWindow = new google.maps.InfoWindow({
content : conString,
position : customPosition,
maxWidth : 350
});
this.infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
ERRORS:
The values are in the textbox are getting null(sometimes) for both the textbox which was triggered by infoWindow.
Regards,
ArunRaj.
It seems that root cause of problem is that user is allowed to draw several polygon before infowindow Region Name and Description are written and Save Region is pressed. If you draw many polygons and infowindows are opened when you click Save Region from the last one, information is sent from the first one polygon. So, if nothing is written for the first one polygon you will get empty values like:
Object {data: ug, regionName: "", regionDescription: ""}
I'd prevent drawing of polygons until information is not sent using Save Region using drawingTool.setDrawingMode(null);:
function displayInfo(conString, customPosition) {
console.log('this');
console.log(this);
this.infoWindow = new google.maps.InfoWindow({
content : conString,
position : customPosition,
maxWidth : 350
});
drawingTool.setDrawingMode(null);
this.infoWindow.open(map);
}
and enabling it again after information about name and description is collected:
function get_point_info(vertices) {
var vertice = vertices;
var RegionName = document.getElementById('region_name').value;
var RegionDesc = document.getElementById('region_desc').value;
this.infoWindow.close();
polygonJson = {
data : vertice,
regionName : RegionName,
regionDescription : RegionDesc
};
console.log('Object.toJSON(polygonJson)');
console.log(polygonJson);
drawingTool.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
}

To get the position of draggable markers

I am using draggable markers in google maps. I have to get the position of markers after dragging because i have to store the new position of marker
The code is
var m = new GMarker(point,{draggable: true});
m.entry_id = id;
m.isMarker = true;
app.entries[id].marker = m;
Here is my example that will display the new location of the marker in and info-window at the new location after the marker has been dragged:
//assuming u have lat and long as latitude and longitude of the initial position
var location = new GLatLng(lat,long);
var marker = new GMarker(location, {draggable: true});
GEvent.addListener(marker, "dragstart", function() {
map.closeInfoWindow();
});
GEvent.addListener(marker, "dragend", function() {
var latlng = marker.getLatLng();
marker.openInfoWindowHtml("New Lat : " + latlng.lat() + ", New Long : " + atlng.lng() );
});
Am assuming you are using API version 2, the solution is a bit different for Version 3, but just a matter of change in the calling conventions sort of.

Categories

Resources