How to get the marker position in openlayer - javascript

I have implemented a openlayer map with several markers with drupal. I want to get the longitude and latitude of the marker when I click on the marker. I have just write a code which shows the longitude and latitude when I click on the map. Instead I want to alert the position only when I click on the marker that I have plotted on the map. How to get the longitude and latitude of the marker?
jQuery(function ($) {
var ol_data = $('.openlayers-map').data('openlayers');
var map = ol_data.openlayers;
map.events.register("click", map, function (e) {
var lonlat = map.getLonLatFromPixel(e.xy);
alert("You clicked near " + lonlat.lat + " N, " + +lonlat.lon + " E");
});

This may help you
var markerslayer = map.getLayer('Markers');//get marker layer
var marker = markerslayer.markers[0];//get marker
var lonlat = marker.lonlat;//get marker latlon(position)

I have not found a way to do this in layer scope, but you can do this for every marker in the layer:
marker.events.register('click', marker, function (evt) {
alert("lon: "+evt.object.lonlat.lon+" , lat: "+evt.object.lonlat.lon);
});
jsFiddle: http://jsfiddle.net/Kenny806/SmMxW/1/
The problem with this attitude is, that with many markers you will get a lot of registered events and possibly performance issues.

Related

Get the list of coordinates of all markers in leaflet

I am trying to make a web map in which I can add a marker on map and at the same time get the lat lon coordinates of all markers to be saved on my database later on. I came up with this function to do that:
function newMarker(e) {
var new_mark = L.marker()
.setLatLng(e.latlng)
.addTo(map_4562f93a48a3459d95c4d292f52b5adc);
new_mark.dragging.enable();
new_mark.on("dblclick", function(e) {
map_4562f93a48a3459d95c4d292f52b5adc.removeLayer(e.target);
});
var latlngs = [];
var lat = e.latlng.lat.toFixed(4),
lng = e.latlng.lng.toFixed(4),
mark_latlon = new_mark.getLatLng();
map_4562f93a48a3459d95c4d292f52b5adc.eachLayer(function(layer) {
latlngs.push(mark_latlon);
console.log(latlngs);
});
new_mark.bindPopup("Waypoint");
}
map_4562f93a48a3459d95c4d292f52b5adc.on("click", newMarker);
The problem with this code is that it just adds the coordinates of the last marker every time a marker is created by clicking. I want all the coordinates to be appended to latlongs Array. And if possible I want to it to be updated when deleted or dragged. Can anyone help me on this?

jQuery/Javascript: Google Maps: How to toggle multiple pins on a map?

I have a database of locations which I want to be able to print on a map. Ideally there should be one map with multiple pins for each location you have toggled on. So click a button for location X and it shows up on the map. Click the button for location Y and it shows up on the same map. Click X again and it hides from the map.
Currently I have it so I click on X and the map gets redrawn centered around point X.
Here is the HTML for each button:
<input type='button' data-lat='38.89864400' data-long='-77.05283400'
data-when='20 Aug at 2:00am' value='Location X' class='click' />
The jQuery I'm using is:
jQuery(document).ready(
function initialize() {
jQuery("input.click").click(function() {
showOnMap(jQuery(this).data('lat'), jQuery(this).data('long'), jQuery(this).data('when'));
});
}
);
function showOnMap(lat, long, message) {
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: message
});
google.maps.event.addDomListener(window, 'load', showOnMap);
}
Is there an easy way to switch from what I have to what I want? I've searched for a while but no one seems to be asking this use case in a browser, just Android (which I'm not doing).
Thanks!
There is an example in the documentation on how to hide/show markers. In short, a marker is:
hidden by setting its map to null
showed by setting its map to map
To do so, you will need to access each marker individually. If you have a definite number of locations, it can be done by naming them with different names (eg var markerLocationX, var markerLocationY, etc). Otherwise, the markers need to be stored in an array.
Supposing you have a definite number of known locations to toggle the markers, your javascript code may look like this:
function toggleMarker(markerName) {
if (markerName.getMap() == null) {
markerName.setMap(map);
} else {
markerName.setMap(null);
}
}

Zoom in into a marker using JavaScript link

I'm a beginner in google maps and JavaScript.
I'm creating a random markers on google map using Maps API V3, I want to create a list on the side that contain all Markers Id so when i click on Marker ID it will zoom in, on the map to show the marker. specifically i want to know how to create that link in javascript
thank you
This answer is from beginner to beginner ;) I like benastan's answer for succinctness and the application of closure, still I'd like to show a more "basic" approach by writing functions.
I don't feel qualified to talk about closures and function scopes, but I can say from experience these closure "wrappers" prevent unexpected behavior from functions called within loops or within other functions. One such bug could be a loop iterator value ending up all the same value (last iteration) or undefined. (my own example)
Link to full code: http://jsfiddle.net/WaWBw/
Click on the map to place markers, and clicking on markers or links on the side zooms in.
function addMarker(pos) {
var marker = new google.maps.Marker({
map: map,
position: pos
});
markers.push(marker);
count = markers.length - 1;
addMarkerListener(marker, count, 6);
makeDiv(count, 4, "Marker #");
count++;
}
function addMarkerListener(marker, index, zoomLevel) {
google.maps.event.addListener(marker, 'click', function(event) {
zoomIn(index, zoomLevel);
});
}
function makeDiv(index, zoomLevel, content) {
document.getElementById("sidebar").innerHTML += '<div onclick="zoomIn(' + index + ',' + zoomLevel + ')">' + content + ' ' + index + '</div>';
}
function zoomIn(index, zoomLevel) {
map.setCenter(markers[index].getPosition());
map.setZoom(zoomLevel);
}
Say you have a set of lat/lng coordinates:
var coords = [[32, -70], [50, -10], [0, 20]];
Loop through the coordinates, plotting the marker on your map and generating the list items. Bind the click handler at the same time:
var tpl = 'Click here to view a point';
// Loop through coordinates.
for (var i in coords) {
// Create a closure.
(function() {
var pt = coords[i],
latlng = new google.maps.LatLng(pt[0], pt[1]),
marker = new google.maps.Marker({
position: latlng,
map: map // variable containing your google map.
}),
elm = document.createElement('li');
elm.innerHTML = tpl;
// When you click the list item, set map center to latlng of marker.
elm.onclick = function() {
map.setCenter(latlng);
};
document.body.appendChild(elm);
})();
}

Google Maps API - Display info for all markers with same lat/long

I am mapping some concert locations on google maps, using data from Songkick.com's API. I'm making a call to the data using jQuery. When mapping a concert, if a single venue has multiple concerts scheduled, all of the markers are placed in the exact same location. This means that only the marker of the most recent concert is visible, and the google maps infoWindow only displays the data for that most recent concert.
I would like to make it so that all concerts taking place at that exact same lat/long display their info in the infoWindow. So when you click on the marker, all scheduled shows are displayed in the infoWindow, not just the most recent show.
Here is part of my javascript:
function doSearch(locations) {
deleteOverlays();
jQuery.getJSON("http://api.songkick.com/api/3.0/search/locations.json?query=" + locations + "&apikey=XXXXXXXX&jsoncallback=?", function(data){
var id = data.resultsPage.results.location[0].metroArea.id;
jQuery.getJSON("http://api.songkick.com/api/3.0/metro_areas/" + id + "/calendar.json?apikey=XXXXXXXX&jsoncallback=?", function(data){
var bounds = new google.maps.LatLngBounds();
var point;
$.each(data.resultsPage.results.event, function(i, item) {
var event = item;
point = new google.maps.LatLng(
parseFloat(item.location.lat),
parseFloat(item.location.lng));
var marker = new google.maps.Marker({
map : map,
animation: google.maps.Animation.DROP,
position : point
});
markersArray.push(marker);
var contentString = '<p><b>' + item.displayName + '</b></p>' + '<p>' + item.location.city + '</p>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
if (currentInfoWindow != null) {
currentInfoWindow.close();
}
infowindow.open(map, marker);
currentInfoWindow = infowindow;
});
To see this application in action, I have set up a temporary website.
http://129.219.78.186/~masgis/tward/songkick/Metro.html
To see what I am talking about, type in the name of a major city, and click a marker that drops. Only the most recent concert will show up.
Thanks in advance, any help is much appreciated.
It looks like the SongKick API call returns a unique ID for each venue. So here's what you can do:
Add each event object to an array.
Pull out unique venue IDs from the events in the array.
Loop through each unique venue ID, pulling out each event with that venue ID, and build the info window string by looping through this subset of events.
Build the marker using the venue info, setting the info window string to the marker.
It's a bit of JavaScript code, nested loops, and a bit of a performance hit, but it should do the trick.

Google Maps Api: How to add a marker and speech bubble?

I have managed to get a google map on my site using Javascript api of google maps.. and it works great...
Can anyone tell me how i can add the Speech bubble and marker ... Pictured here... http://code.google.com/apis/maps/
Basically my site displays a simple map but its missing the marker for where office is and a speech bubble where i want to place the office address
Any help would be really appreciated.
Here is the code i have so far
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.466997, -3.705482), 13);
}
A marker can be added using the GMarker class ; for instance, to add a point to a map, I would use something like this :
var point = new GPoint(45.779915302498935, 4.803814888000488);
var marker = new GMarker(point);
map.addOverlay(marker);
(Of course, you'll have to adapt the coordinates to the ones of your office, so it doesn't point to some point in France ^^ ; I suppose the ones you posted should do the trick ;-) )
And for an Information window, you can use the GMarker.openInfoWindowHhtml method, on your marker.
I guess something like this should do the trick :
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.466997, -3.705482), 13);
var point = new GPoint(-3.705482, 40.466997);
var marker = new GMarker(point); // Create the marker
map.addOverlay(marker); // And add it to the map
// And open some infowindow, with some HTML text in it
marker.openInfoWindowHtml(
'Hello, <strong>World!</strong>'
);
}
And the result looks like this :
(source: pascal-martin.fr)
Now, up to you to build from here ;-)
Here is some code that shows how to use an XML file to load multiple markers. Also this site is the best there is for Google Maps examples and tutorials
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
//gmarkers.push(marker);
// add a line to the side_bar html
//side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
$(document).ready(function(){
// When class .map-overlay-right is clicked map is loaded
$(".map-overlay-right").click(function () {
var map = new GMap2(document.getElementById('map-holder'));
$("#map-holder").fadeOut('slow', function(){
var gmarkers = [];
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
// Get XML file that contains multiple markers
$.get("http://www.foo.com/xml-feed-google-maps",{},function(xml) {
$('marker',xml).each(function(i) {
// Parse the XML Markers
html = $(this).text();
lat = $(this).attr("lat");
lng = $(this).attr("lng");
label = $(this).attr("label");
var point = new GLatLng(lat,lng);
var marker = createMarker(point,label,html);
map.addOverlay(marker);
});
});
});
$("#map-holder").fadeIn('slow');
var Asia = new GLatLng(19.394068, 90.000000);
map.setCenter(Asia, 4);
});
});

Categories