Passing map object to javascript function - javascript

In order to add an offset to the center point in Google maps when a button are pressed, I try this funcion:
function offsetCenter(map, marker) {
var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(marker.getPosition());
var pixelOffset = new google.maps.Point((100/scale) || 0,(0/scale) ||0)
var worldCoordinateNewCenter = new google.maps.Point(
worldCoordinateCenter.x - pixelOffset.x,
worldCoordinateCenter.y + pixelOffset.y
);
var newCenter = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter);
map.setCenter(newCenter);
}
});
I call that funcion from infoWindows where map and marker are defined:
(function(marker, data) {
google.maps.event.addListener(marker, "click", function() {
info = '<h4>' + data.nombre + '</h4><h4>'+ data.offerta+'</h4><h4>'+ data.horario+'</h4><a href='+data.web+'><h4>Web</h4></a>'
+ '<input type="button" class = "launchConfirm" onclick="offsetCenter(\''+map+'\', \''+marker+'\');" value='Reset center'></input>' //this is the button inside the infowindos to re-set the map center with an offset
;
infoWindow.setContent(info);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition()); //center the map to marker
map.setZoom(16); //zoom to marker
});
}
But marker and map object are not defined inside the offsetCenter function.
How can pass a map object and marker to that function?

make sure your 'map' variable and your marker manager are in scope >= function scope. this way you will not need to pass in the map.
Use a marker manager to manage your makers. you can then add a unique id to some attribute on your link. when the click comes in you can access the object to get the id, which will allow you to retrieve the maker from the manager. so the code would look something like this:
Info Window Content(shortened for brevity):
var info = '<h4>' + data.nombre + '</h4>'<input type="button" data-markerId="' + SomeMarkerManager.getMarkerId() '" onclick="offsetCenter(this);" value='Reset center'></input>'
var offsetCenter = function (element) {
// get the marker Id
var markerId = $(element).attr("data-marker-id");
// use the markerId to find your marker
var marker = SomeMarkerManager.getMarkerById(markerId);
// now you have access to your map and the clicked marker
}
P.S.
marker managers are out of the scope of this answer. Just search for google maps marker managers.

Related

Iterate Over Table with jQuery and Create a New Variable from Element Value

I've iterated over a table with javascript so I can use the data as a variable for creating markers on a Google Map. My map and the code that iterates over the table both work, but I cannot figure out how to make the gridmap value available inside my marker variable. I assume I need to do a for loop around my marker variable, which I can probably figure out, I am simple stuck on taking my element variables, and making them available as variables for my markers. Below is my code, if this makes any sense. I've been at this for hours and it is 3:30am; I will refractor the question in the morning if needed. Thank you.
This is the updated and working code:
I iterated over the DOM to grab the <tr> elements from tbody only. Note the tr:gt(0) part - this skips the first header row. Then I create a new array by filtering out the markers against the gdata array. I still need to clean this up a bit add more functionality like clustering, but I am very happy at this point and hopefully this will help someone else.
<script>
function initMap() {
var map;
var table = $("table");
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var htmlLabel = labels.split(""); // Add Labels to Html Columns for Matching
var gdata = new Array();
$("table tbody tr:gt(0)").each(function (i) {
gdata[i] = new Array();
$(this).children('td').each(function (ii) {
gdata[i][ii] = $(this).text();
});
});
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'satellite',
disableDefaultUI: true,
scrollwheel: false,
draggable: true
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
['a0', 32.840801, -117.244842],
['a10', 32.840801, -117.244842],
['a20', 32.840777, -117.244864],
['a30', 32.840758, -117.244881],
['a40', 32.840732, -117.244899],
['aa0', 32.840828, -117.244794],
['aa10', 32.840828, -117.244794],
['b0', 32.840624, -117.24493],
['b10', 32.840624, -117.24493],
['b20', 32.840594, -117.244928],
['b30', 32.840567, -117.244924],
['b40', 32.840544, -117.244918],
['b60', 32.840544, -117.244918],
['bb0', 32.840495, -117.244897],
['bb10', 32.840495, -117.244897],
['bb20', 32.840468, -117.244885],
['c0', 32.84082, -117.244712],
['c10', 32.84082, -117.244712],
['c20', 32.840815, -117.244729],
['c30', 32.840806, -117.244749],
['c40', 32.840793, -117.244767],
['c50', 32.840779, -117.244789],
['c70', 32.840755, -117.244816],
['cc0', 32.840828, -117.244661],
['cc10', 32.840828, -117.244661],
['d0', 32.840607, -117.244867],
['d10', 32.840607, -117.244867],
['d20', 32.840586, -117.24486],
['d30', 32.840567, -117.244856],
['d40', 32.840543, -117.244841],
['d50', 32.840514, -117.244824],
['dd0', 32.84046, -117.244774],
['dd10', 32.84046, -117.244774],
['e0', 32.840788, -117.244598],
['e10', 32.840788, -117.244598],
['e20', 32.840791, -117.24462],
['e30', 32.840788, -117.244644],
['e40', 32.840787, -117.244665],
['e50', 32.840783, -117.244687],
['e60', 32.84078, -117.244707],
['e70', 32.840769, -117.244729],
['ee0', 32.84078, -117.244539],
['ee10', 32.84078, -117.244539],
['f10', 32.840607, -117.244809],
['f20', 32.840586, -117.244802],
['f30', 32.840564, -117.244785],
['f40', 32.840543, -117.244765],
['f50', 32.840532, -117.244749],
['f60', 32.840519, -117.244731],
['f70', 32.840508, -117.244714],
['ff0', 32.840473, -117.244632],
['ff10', 32.840473, -117.244632],
['g0', 32.840709, -117.244468],
['g10', 32.840709, -117.244468],
['g20', 32.840718, -117.244484],
['g30', 32.840737, -117.244499],
['g40', 32.840739, -117.244515],
['g50', 32.840747, -117.244531],
['h0', 32.840681, -117.244569],
['h10', 32.840681, -117.244569],
['h20', 32.840707, -117.244574],
['i0', 32.840611, -117.24458],
['i10', 32.840611, -117.24458],
['i20', 32.840576, -117.24461]
];
var filteredMarkers = []; // the results array
for (var iii = 0; iii < gdata.length; iii++) // iterate for every marker key
{
filteredMarkers = filteredMarkers.concat(markers.filter(function (item) {
return item[0] == gdata[iii][0];
}));
}
console.log(filteredMarkers);
console.log(gdata);
console.log(markers);
// Info Window Content
var infoWindowContent = [
['<div class="">' +
'<h3>Add Code Here</h3>' +
'<p>Add Code Here</p>' + '</div>']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < filteredMarkers.length; i++) {
var position = new google.maps.LatLng(filteredMarkers[i][1], filteredMarkers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: filteredMarkers[i][0],
label: labels[labelIndex++ % labels.length]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
this.setZoom(24);
google.maps.event.removeListener(boundsListener);
});
}
</script>
It appears you're also using Angular and that the id='gridmap' div is returning the object name and not the content. The nature of the div content looks like the crux of problem and so would suggest looking at this SO question: How to show object property with Angularjs
From here if you can generate HTML that looks something like this below after Angular has done its thing, keeping the property out of view by inserting its elements into data tags:
<tr>
<td> ..... </td>
<td> ..... </td>
<td> ..... </td>
<td class='gridmap' data-lat='23.424' data-lng='-117.233'>a0</td>
</tr>
If you insert the whole object including curly brackets you may have to do additional JSON stringification and parsing which at this point are better avoided.
Note that HTML id labels should only used for unique DOM elements, so if you have more than one table row it should be a class (which also means adjusting your css accordingly)
Now we can use jquery data to interrogate the same HTML cell tag and pass to grLat and grLng variables :
$('tr').each(function (i) {
var $tds = $(this).find('td').eq(8), // moved the eq(8) here
gLabel = htmlLabel[i],
gridmap = $tds.text(),
grLat = Number($tds.data('lat')), // get the lat data
grLng = Number($tds.data('lng')); // get the lng data
console.log(
'Marker:' + gLabel
+ '\nRow:' + (i + 1)
+ '\nGrid Map: ' + gridmap
+ '\nGrid lat: ' + grLat
+ '\nGrid lng: ' + grLng // check components
);
var marker = new google.maps.Marker({
position: {lat: grLat, lng:grLng}, // recomposed object
map: map,
label: labels[labelIndex++ % labels.length],
animation: google.maps.Animation.DROP
});
})
This should put you in a better position to debug

Google Maps with Multiple Information in one marker

I am developing a web application that contains some information about place. That place may have more than one agenda. Can I show more information in one marker, such as stack balloon?
This is my maps
http://petamajelis.org/maps/index.php
This is my data
http://petamajelis.org/maps/ajax2.php
there are some places that have more than one agenda, and I want to show all of that agendas in one marker if the latitude and longitude are same.
this is my code to show marker depend on database, I put it in index.php
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(-6.270293,106.830995),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("ajax2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var materi = markers[i].getAttribute("materi");
var pemateri = markers[i].getAttribute("pemateri");
var tanggal = markers[i].getAttribute("tanggal");
var hari= markers[i].getAttribute("hari");
var jam= markers[i].getAttribute("jam");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<br/>" +materi+ " : "+pemateri+ "<br/>"+ hari +" "+tanggal+ " Jam : "+jam;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
could i modify that code to show some information if latitude/longitude are same and show it in a balloon above marker?
thanks before
Possible way to achieve it(there may be many ways):
create some object at the begin of the callback of downloadUrl()
var markerContents={};
inside the loop where you create the markers populate this object with properties. As name for the properties assign the string-representation of the point(will be returned by LatLng.toString()). Create a variable of this string:
var markerId = point.toString();
First you have to check now if this property already exists, when not create it and set the value to an empty array:
if(!markerContents[markerId]){
markerContents[markerId] = [];
}
Then, after the line where create the html, push the html into the array:
markerContents[markerId].push(html);
to avoid the creation of multiple markers at the same position, leave the current iteration before you create the marker, when there are more than 1 item inside the array:
if(markerContents[markerId].length>1){return;}
modify the call of bindInfoWindow(); , pass the array as argument instead of html
bindInfoWindow(marker, map, infoWindow, markerContents[markerId]);
Modify the click-listener of the Marker so that he may use the content of the array as InfoWindowContent
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html.join('<hr/>'));
infoWindow.open(map, marker);
});
}
There will no longer be multiple markers at the same position, instead there will be 1 marker with the content set to the html of all markers with this position, delimited by a horizontal rule.

How to get the marker position in openlayer

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.

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