I’m having problems upgrading to Google Maps v3 from v2. In particular with MarkerManager. I haven’t worked with maps before and am helping out someone whose developer abandoned them who developed the maps in v2.
The map is to show a maximum of 100 markers that when clicked on show an infobox. (There is also a telerik RadGrid bound to with the results.) It all seems to work until it gets into DisplayAllMarkers() mgr.addMarkers() (see below). It fails in ProjectionHelperOverlay.prototype.LatLngToPixel with Uncaught TypeError: Cannot call method ‘lng’ of undefined. I’ve tried putting in alerts in AddMarker if lat or lng are undefined, but none were alerted. The previous calls to MarkerManager.prototype.addMarkerBatch_ set mPoint to undefined which was then passed to getTilePoint which calls LatLngToPixel where it fails.
I’m thinking it’s a problem with listeners, but have tried various listeners without success. I would really appreciate some help with this as I have been unable to make progress for some time and am letting down the client and don’t know what to try next.
Select SearchResult.js snippet of code:
$(document).ready(function () {
InitializeMap(originalScale);
});
var map;
var batch = [];
var mgr;
var geocoder = null;
function InitializeMap(scale) {
map = new google.maps.Map(
document.getElementById('MapContainer'), {
center: new google.maps.LatLng(Latitude, Longitude),
zoom: scale,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var listener = google.maps.event.addListener(map, "bounds_changed", function () {
MapMoved();
google.maps.event.removeListener(listener);
});
}
var south, west, north, east, zoom;
function MapMoved() {
zoom = map.getZoom();
//zoom = map.setZoom();
var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
south = sw.lat();
west = sw.lng();
north = ne.lat();
east = ne.lng();
Search();
}
The Search(); loads up the search parameters (including the north, south, east, west co-ordinates) and calls a telerik ajax request.
C# snippet:
if (Properties.Count >= 1 || zoom == "0") //display properties
{
RadAjaxManager1.ResponseScripts.Add("ClearAll();");
Properties.ForEach(p =>
{
string script = "AddMarker(" + p.ID.ToString() + "," + p.LatitudeShort.ToString() + "," + p.LongitudeShort.ToString() + ");";
RadAjaxManager1.ResponseScripts.Add(script);
});
RadAjaxManager1.ResponseScripts.Add("DisplayAllMarkers();");
}
else //zoom out map – which will start the search process all over again.
{
string delta = "1";
RadAjaxManager1.ResponseScripts.Add("ZoomOut(" + delta + ");");
}
SearchResult.js snippet continued:
function ClearAll() {
batch = [];
}
function AddMarker(id, lat, lng) {
batch.push(CreatePropertyMarker(lat, lng, id));
}
function DisplayAllMarkers() {
mgr = new MarkerManager(map, { trackMarkers: true });
google.maps.event.addListener(mgr, 'loaded', function () {
mgr.clearMarkers();
mgr.addMarkers(batch, 3, 17); // **Failing in here!!!**
mgr.refresh();
});
}
function CreatePropertyMarker(lat, lng, id) {
var redIcon3 = {
url: '../images/HouseIcon_ForGoogleMap.png',
size: new google.maps.Size(22, 22),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 22)
};
var marker3 = new google.maps.Marker(new google.maps.LatLng(lat, lng), redIcon3);
google.maps.event.addListener(marker3, 'click', function () {
var data = "{'Id': '" + id + "'}";
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: 'searchresult.aspx/GetPropertyPopOut',
data: data,
success: function (data) {
var popout = data.d;
marker3.openExtInfoWindow(map, "custom_info_window_red", popout, { beakOffset: -1 });
},
error: function (result) {
alert('status:' + result.status + ' statusText:' + result.statusText);
}
});
});
return marker3;
}
Script order and versions:
jquery-ui-1.9.1.custom.min.css
Google Maps: v3 (I have also tried specifying particular version 3 numbers e.g. v=3.12 http://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false
jquery-1.8.2.js
jquery-ui-1.9.1.custom.min.js
extinfowindow.js v2.0
MarkerManager.js v1.1
SearchResult.js
jquery-ui-1.8.16.custom.min.js
jquery-1.6.2.min.js
After tying a load of different things I eventually found out the problem was when creating the marker it needed position set. I changed the line in CreatePropertyMarker from:
var marker3 = new google.maps.Marker(new google.maps.LatLng(lat, lng), redIcon3);
to:
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
icon: redIcon3
});
Related
I have two websites which attempt to display a map of bushfires in an area, using the Google Maps javascript api and a GeoJson from the NSW RFS. Both are resposive sites.
The maps seem very twitchy about displaying the actual map background, and in one case I always get a grey background (though markers etc are properly displayed).
This seems to be related to the way the map canvas is sized; if a fixed width and height are set then all is well, but if % are used grey is displayed. In the one case setting width and height in vw (% of viewport width) works, but in the other it does not.
The site that works is http://lansdowne.rfsa.org.au/firemap.php
the one that does not is http://www.upperlansdownehall.org.au/firemap/ - if you zoon out to a larger area ytou will see that markers appear in both maps.
The major difference is that one is Wordpress, with the javascript enqueued with the footer, while the other is imbedded in the html.
I have tried setting the size (width and height) of the map-canvas in js (or that of an enclosing division) using the following code either in the initilize routine or just before the addDomListener(window, 'load', initialize);
var mw = document.getElementById('map-canvasout').offsetWidth;
var mw = document.documentElement.clientWidth * .5;
var mh = mw * .75;
var mhx = mh + "px";
var mapara = document.getElementById('map-canvasout');
mapara.style.height= mhx;
I would be very grateful for any ideas, as I am out of them. code for the wordpress scripts encode and js follows:-
add_action('wp_enqueue_scripts', 'ulmh_googlemaps', 105);
function ulmh_googlemaps(){
if (is_page('32') || is_page('233')) {
wp_register_script( 'gmap', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBAlriyR-tmJU4jrd0z9nmWEmw4XSS0nC0',true);
wp_register_script( 'ulmh_gmap', plugins_url( 'firemap.js', __FILE__ ),true);
wp_enqueue_script('gmap');
wp_enqueue_script('ulmh_gmap');
}
}
function initialize() {
var lat = -31.71 ;
var lng = 152.47;
var zom = 12;
var nam = "Upper Lansdowne";
var mapOptions = {
center: { lat: lat, lng: lng},
zoom: zom
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.data.loadGeoJson('http://www.upperlansdownehall.org.au/wp-content/uploads/majorIncidents.json');
map.data.setStyle(function(feature) {
var IconBase = 'http://www.rfs.nsw.gov.au/_designs/geojson/fires-near-me/images/';
var image = {
url: IconBase + 'watch-and-act.png',
size: new google.maps.Size(27, 27),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(14, 13)
};
var ctg = feature.getProperty('category');
switch (ctg) {
case "Emergency Warning": image.url = IconBase + 'emergency-warning.png'; break;
case "Watch and Act": image.url = IconBase + 'watch-and-act.png'; break;
case "Advice": image.url = IconBase + 'advice.png'; break;
default: image.url = IconBase + 'not-applicable.png';
}
return {
icon: image
};
});
var infowindow = new google.maps.InfoWindow();
map.data.addListener('click', function(event) {
var ef = event.feature;
var myHTML = '<b>'+ef.getProperty("title") + '</b></br>' + ef.getProperty("description");
infowindow.setContent("<div style='width:250px;'>"+myHTML+"</div>");
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,0)});
infowindow.open(map);
});
nam = 'Fire Map of the ' + nam + ' Area';
lat = Math.round(lat*10000)/10000;
lng = Math.round(lng*10000)/10000;
google.maps.event.addListener(map, 'idle', function() { // 'bounds_changed'
google.maps.event.trigger(map, 'resize');
var mapbnd = map.getBounds();
var nbrfre = 0;
map.data.forEach(function(feature) {
var geo = feature.getGeometry();
if (geo.getType() == 'Point') {
var LatLng = geo.get();
if (mapbnd.contains(LatLng)) {
nbrfre = nbrfre +1;
}
} else if (geo.getType() == 'GeometryCollection') {
var LatLng = geo.getAt(0).get();
console.log(LatLng);
if (mapbnd.contains(LatLng)) {
nbrfre = nbrfre +1;
}
}
});
var fretxt = ' (No Fires)';
if (nbrfre == 1) {
fretxt = ' (1 Fire)';
} else if (nbrfre > 1) {
fretxt = ' (' + nbrfre + ' Fires)';
}
var ctr = map.getCenter();
clt = Math.round(ctr.lat()*10000)/10000;
cln = Math.round(ctr.lng()*10000)/10000;
if ((clt != lat) || (cln != lng) ||(zom != map.getZoom())) {
nn = 'General Fire Map';
} else {
nn = nam;
}
var pstttl = document.getElementsByClassName("posttitle");
pstttl[0].innerHTML = nn + fretxt;
if (nbrfre != 0) {
pstttl[0].style.backgroundColor='red';
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Well it seems my unconscious is better at this than the rest of me, as I woke up this morning with a partial answer. One site was using the experimental version of Google Maps (by default) while the other specified v=3 and therefore got the release version.
Of course that raises the question of what is happening at Googles end, but I’ll chase that up with them.
Thanks to anyone who looked at the question.
I am using ionic to display benefits data on Google map. It works fine except on click of any marker, it opens the last markup content. Follownig is my google map js code
.controller('BenefitsMapCtrl', function ($scope, LocationBenefits, Utilities, $ionicLoading, $compile) {
$scope.init = function () {
var userId = Utilities.getUserId();
LocationBenefits.getLocationBenefits(userId, function (userBenefits) {
console.log("Got location benefits data for Google mp for user id "+userId);
$scope.userBenefits = userBenefits;
var centerLatlng;
if (typeof $scope.userBenefits !== "undefined" && $scope.userBenefits.length > 0) {
var firstBenefitLocation = $scope.userBenefits[0];
centerLatlng = new google.maps.LatLng(firstBenefitLocation.location.lat, firstBenefitLocation.location.lng);
}
var mapOptions = {
center: centerLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.markers=[];
//Loop in each benefits and place on Google map
if (typeof $scope.userBenefits !== "undefined" && $scope.userBenefits.length > 0) {
for (var i = 0; i < $scope.userBenefits.length; i++) {
var benefit = $scope.userBenefits[i];
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><div><img class='shop-icon' src='" + benefit.shopicon + "' alt='" + benefit.shopName + "'/><span class='item-text-wrap'>" + benefit.shopName + "</span></div><div class='shop-offer'>"+benefit.benefits.short_benefitText+"</div><div class='card'><img class='card-art' src='"+benefit.cardart+"' alt='"+benefit.card+"'/></div></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
//Get location
var locationLatLng = new google.maps.LatLng(benefit.location.lat, benefit.location.lng);
var marker = new google.maps.Marker({
position: locationLatLng,
map: map,
title: benefit.shopName
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
$scope.markers.push(marker);
}
}
//Finally set the map
$scope.map = map;
});
};
// google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function () {
if (!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function (pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function (error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function () {
alert('Example of infowindow with ng-click')
};
});
Issue: On click of any markup on Google map, it always opens the last markup.
Please help.
I had the same problem and spend a lot of time to figure out what's going on so I'd like to add the answer for the future generations,lol.
First of all it's a good idea to refer to official Google maps API docs and take a look at "Events section". I found there one interface of adding event listeners to markers that I never seen before(even after googling this issue for few hours).
marker.addListener('click', function() {});
google.maps.event.addListener(marker, 'click', function () {});
It pointed me out to the idea that when you are trying to do it in the loop using an "old" way, your marker variable is obviously equals to the last element of your markers array. And when event really can be triggered your initialization process is finished what means that your variable has always wrong value in anonymous function at the moment it can be really called. So, again, you didn't passed marker as a parameter to that anonymous event handler.
But you still can do what you want. Just use this.inside your event handler. Bellow is my code sample
marker.addListener('click', function() {
var it = this;
$scope.$apply(function() {
$scope.activeEvent = EventService.getShort($scope.events[it.id]);
});
});
I believe that you can try to use this. in "old-style" interface as well.
I had the same problem and I found the solution here. Apparently, you just have to create a function to create the markers and call that function inside the for loop:
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = map; //Attach the map to the scope before adding the markers
$scope.markers=[];
var infowindow = new google.maps.InfoWindow();
var createMarkers = function (benefit){
//Info window's content
var contentString = "<div><div><img class='shop-icon' src='" + benefit.shopicon + "' alt='" + benefit.shopName + "'/><span class='item-text-wrap'>" + benefit.shopName + "</span></div><div class='shop-offer'>"+benefit.benefits.short_benefitText+"</div><div class='card'><img class='card-art' src='"+benefit.cardart+"' alt='"+benefit.card+"'/></div></div>";
var compiled = $compile(contentString)($scope);
//Get location
var locationLatLng = new google.maps.LatLng(benefit.location.lat, benefit.location.lng);
//Create marker
var marker = new google.maps.Marker({
position: locationLatLng,
map: map,
title: benefit.shopName
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(compiled[0]);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
//Loop in each benefits and place on Google map
if (typeof $scope.userBenefits !== "undefined" && $scope.userBenefits.length > 0) {
for (var i = 0; i < $scope.userBenefits.length; i++) {
var benefit = $scope.userBenefits[i];
createMarkers(benefit);
}
}
I should have on my hands what is proper working JS and an xml file...I'm simply trying to take advantage of the huge database of locations that has been offered up as free for everyone to use - located # http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery
I'm tried using their maps.js and xml file...but all I end up with is a blank maps screen...
Here is the Javascript...
/*********************************************
**Google Maps Custom API work**
This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.
Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php
*/
//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder();
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';
//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) {
console.log('view map');
map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type
center: new google.maps.LatLng(latitude, longitude),
zoom: varZoom,
mapTypeId: 'roadmap',
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false
});
//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
console.log('center changed');
//clearMarkers();
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
console.log("loaded");
$("#loading-screen").fadeOut(250, function(){});
$("#loading-icon").fadeOut();
//google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ });
});
//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script
//Pull in the XML feed
downloadUrl(download_file, function(data) {
console.log("downloading xml");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//Loop through all markers in the XML file
for (var i = 0; i < markers.length; i++) {
var state = markers[i].getAttribute("state");
var x = markers[i].getAttribute("lat");
var y = markers[i].getAttribute("lng");
if ( state != 'PR' && state != 'VI' && state != 'GU' && x != "" ){
//console.log(state);
var ids = parseFloat(markers[i].getAttribute("id"));
var z = new google.maps.LatLng(x,y,i);
//console.log(x);
var _id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var zip = markers[i].getAttribute("zip");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var brewery_type = markers[i].getAttribute("type");
var member_type = '';
var member_type = markers[i].getAttribute("member_type");
var offer = markers[i].getAttribute("offer");
var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
html += address + "<br/>" + city + ", " + state + " " + zip;
if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";
//var marker = createMarker(ids, z, title, contentstring);
var marker = new google.maps.Marker({
position: z,
map: map,
title: name,
icon: icon,
html: html,
zindex: i
});
//Add a listener for every icon click
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,this);
//map.setZoom(10);
//map.setCenter(this.getPosition());
console.log(this);
});
gmarkers[ids] = marker;
mapMarkers.push(marker);
if( x && y ){
//console.log(ids);
var infowindow = new google.maps.InfoWindow({content: html});
}
/* google.maps.event.addListener(marker, 'click', function() {
console.log('marker clicked');
});
*/
//bounds.extend(z);
//map.fitBounds(bounds);
}//end check for US states only!
} //end for loop
var mcOptions = {gridSize: 60, maxZoom: 9};
var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers
});
} //End full function to create map
/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
console.log('clicked a title ' + i);
smoothScroll("#primary");
var lat = parseFloat(gmarkers[i].position.k);
var lng = parseFloat(gmarkers[i].position.B);
console.log(lat);
map.setCenter({lat: lat, lng: lng});
map.setZoom(13);
google.maps.event.trigger(gmarkers[i], 'click');
};
function createMarker(ids, z, title, contentstring){
console.log('createMarker');
var marker = new google.maps.Marker({
position: z,
map: map,
title: title,
html: contentstring,
icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,marker);
});
gmarkers[ids] = marker;
//console.log(gmarkers[ids]);
};
/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/
function findAddress(position) {
//Let's determind if we have a state (address) or LatLng
var addressStr = $("#state_select li.active").data('state-id');
if (addressStr != 'Select a State') address = "US State of "+addressStr;
if(position) {
var lat = parseFloat(position['latitude']);
var lng = parseFloat(position['longitude']);
var latlng = new google.maps.LatLng(lat, lng);
//console.log(latlng);
}
//Now let's geocode - two different cases
if (geocoder && position) { //If LatLng
//console.log('near me');
geocoder.geocode( { 'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(13);
}
} else {
alert("No results found");
}
}
});
} else if (geocoder && address!="") { //If State
//console.log('by state');
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(6);
}
} else {
alert("No results found");
}
}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
}
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);
}
function doNothing() {}
And here is the link to the xml file....
http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml
I've spent days doing google searches and testing different sections of code to at least get a basic google map to show up via the xml file markers...but to no avail - Any help would be tremendously appreciated!!
~Cheers
EDIT:
Everything worked as expected once I included the following script inline on the page prior to calling the maps.js file. Thanks everyone!
<script>
$(document).ready(function(){
var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php
});
</script>
Looking at the html and the code you provided above I constructed a fiddle for you:
http://jsfiddle.net/loanburger/qafsex5x/
I added two markers in an xml string at the top in the fiddle.
I basically parse the xml doing this:
var markers = $(xml).find("marker");
Its then simply the same for loop you had:
for (var i = 0; i < markers.length; i++)
{
...
}
The fiddle will show you the markers.
I'm managing this website: http://www.gprprojecten.nl
Basically what I'm doing with is is getting a stream of data from a webservice and chaching this. Afterwards I do all kinds of things to this data, including displaying all the projects on a google map.
Problem is, that as the projectnumber grows, the (custom)pins start to overlap (not visible, not clickable).
So I want to cluster my pins.
I started working on a google maps clusterer library using A32.blog as my starting point.
But now a problem arises. As I have chosen a client side filter system called filter.js, I depend on that way of using google maps, which is with objects rather then an array of markers as used in the clusterer library.
Here is the code I use to generate my map in combination with filter.js:
var googleMap = {
center_lat_lng: [52.14, 5.3],
map: null,
markers: {},
addMarker: function (project) {
var that = this;
var image = new google.maps.MarkerImage('#Url.Content("~/Content/img/marker.png")',
new google.maps.Size(63, 27),
new google.maps.Point(0, 0),
new google.maps.Point(23, 27));
var marker = new google.maps.Marker({
position: new google.maps.LatLng(project.loclat, project.loclong),
map: this.map,
title: project.gebouwnaam,
icon: image
});
marker.info_window_content = "<div class=\"gmapcontentwindow\"><h4>" + project.gebouwnaam + "</h4><img src=\"" + project.thumburl + "\" alt=\"" + project.gebouwnaam + "\" /><div class=\"gebouwdata\"><span class=\"date\">" + project.publicatiedatum + "</span><h5>" + project.plaats + "</h5><span>" + project.gebruiksfunctie + " | " + project.gebouwcategorie + "</span><span>" + project.licentiehouder + "</span><span class=\"stars " + project.rating + "\"></span>"
if (project.akkoorddoorexpert == "True") {
marker.info_window_content += "<span class=\"expert\"></span>"
}
var forwardUrl = '#Url.Content("~/Home/Details/")';
marker.info_window_content += "<span class=\"forward\">Lees meer >></b></span></div></div>"
this.markers[project.id] = marker
google.maps.event.addListener(marker, 'click', function () {
that.infowindow.setContent(marker.info_window_content)
that.infowindow.open(that.map, marker);
});
},
updateMarkers: function (filtering_result) {
var google_map = this;
$.each(google_map.markers, function () { this.setMap(null); })
$.each(filtering_result, function () {
google_map.markers[this.id].setMap(google_map.map);
});
},
init: function () {
var options = {
center: new google.maps.LatLng(this.center_lat_lng[0], this.center_lat_lng[1]),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById("gmap"), options)
this.infowindow = new google.maps.InfoWindow({
});
//var markersarray = $(this.markers).toArray();
//console.log(markersarray);
//doet het nog niet???
//http://a32.me/2012/05/handling-huge-amount-of-markers-on-google-maps-with-clusters/
//var markerCluster = new MarkerClusterer(this.map, markersarray, {
// gridSize: 10,
// minimumClusterSize: 2
//});
}
};
project is an object that is passed to the init function from filter.js
You need to add the Marker Clusterer to the global scope or keep a reference to it in your object.
I am trying to get the automatic bounds-and-zoom functions in Google Maps API 3 to work with Ajax/PHP-generated markers and having no luck so far. The PHP-gen map works fine (with manual center and zoom) until I add the bounds-related code, which I got from here at stackoverflow. It now just centers at (0,0) in the middle of the ocean and only the first of my markers displays. The former doesn't seem totally surprising based on the initial center declaration of (0,0), but it worked for the original poster and I'm a Javascript noob so don't really know what I'm doing! I would be eternally grateful if someone could spot the problem.
Here's my current code (I've left out the icon definitions to save space):
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 10,
mapTypeId: '<?php echo $maptype; ?>'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("gen-xml.php?<?php if($country) echo "country=$country"; if($location) echo "&location=$location"; ?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("city");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lon")));
var html = "<div class='infowindow'>" + name + " <br/>" + address + " <br/></div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bounds.extend(myLatLng);
map.fitBounds(bounds);
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);
}
function doNothing() {}
Try
bounds.extend(point);
instead of
bounds.extend(myLatLng);
which seems not to be related to any part of your code