Why Marker Manager doesn't work? - google-maps-api-3

I would use MarkerManager to group neighboring marker in one, I tested an example but it does not work. Different markers are displayed well, but they are not together when they should. The manager is not working as it should, I do not understand why.
<html>
<head>
<title>Test GMap - MarkerManager</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
</head>
<body>
<div id="my-map" style="width:100%;height:700px"></div>
<script>
var maCarte = '';
function initialisation(){
var centreCarte = new google.maps.LatLng(47.389982, 0.688877);
var optionsCarte = {
zoom: 5,
center: centreCarte,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
maCarte = new google.maps.Map(document.getElementById("my-map"), optionsCarte);
// Create a new instance of the MarkerManager
var mgr = new MarkerManager(maCarte);
google.maps.event.addListener(mgr, 'loaded', function() {
console.log('loaded Map');
// Create marker array
var markers = [];
// Loop to create markers and adding them to the MarkerManager
for(var i = 0; i < 50; i += 0.1) {
var marker = new google.maps.Marker({position: new google.maps.LatLng(47.389982 + i, 0.688877 + i)});
markers.push(marker);
}
//var markerCluster = new MarkerClusterer(map, markers);
// Add the array to the MarkerManager
mgr.addMarkers(markers, 8);
// Refresh the MarkerManager to make the markers appear on the map
mgr.refresh();
});
}
google.maps.event.addDomListener(window, 'load', initialisation);
</script>
</body>
Can someone help me?
thank you very much

Your page works for me, but the markers are not immediately visible when the page loads. This is because of the zoom setting you have on line 34:
mgr.addMarkers(markers, 8);
if you set that to a lower number (say, 4) the markers will be visible when zoomed further out.

Related

Google map showing grey bands and looks distorted

For some reason, even though my Google map is showing, there are strange grey bands/lines running through the map (image link below).
Just for reference it uses the places API to search for locations.
Screenshot of the map issue
Anybody have any ideas why this might be? Here's the code for the map:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
<script type="text/javascript">
function search_map_init() {
var args = {
disableDefaultUI : true,
center : new google.maps.LatLng(51.6948168, -0.6433884),
mapTypeId : google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
zoom : 12,
styles : [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}]
};
var map = new google.maps.Map(document.getElementById('map-canvas'), args);
var marker_url = {
url : 'IMG_URL',
scaledSize : new google.maps.Size(48, 65)
};
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location,
icon : marker_url
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
var new_address = $('#pac-input').val();
var new_lat = place.geometry.location.lat();
var new_lng = place.geometry.location.lng();
$('input[name="post[meta_input][map][address]"]').val(new_address);
$('input[name="post[meta_input][map][lat]"]').val(new_lat);
$('input[name="post[meta_input][map][lng]"]').val(new_lng);
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
return map;
}
google.maps.event.addDomListener(window, 'load', search_map_init);
</script>
Note: I've replaced the API key and image URL with API_KEY and IMG_URL in the code above.
I was setting min-width in the CSS for something else which was also effecting the map display. Problem solved!

Google Maps API V3 Z-index Not Working

I have a map with about 20 markers on it representing the birthplaces of ancestors. The markers are created from XML. I want the later generations at the front and the earlier generations behind, but Google Maps defaults to the most southerly markers in front. In its simplest form the code looks like this:
<!DOCTYPE html >
<head>
<link rel="stylesheet" href="css/style.css" type="text/css">
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var thisLatLng = {lat: 51, lng: -3.5};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: thisLatLng,
zoom: 9,
mapTypeId: 'roadmap'
});
// Change this depending on the name of your PHP file
downloadUrl("php-to-xml.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("person");
var gender = markers[i].getAttribute("gender");
var z_index = markers[i].getAttribute("z_index");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var comment = markers[i].getAttribute("comment");
var colour = markers[i].getAttribute("colour");
var html = "<b>" + name + "</b> <br/>" + comment;
var icon = "images/" + gender + "_" + colour + ".png";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon,
optimized: false,
zIndex: z_index
});
}
});
}
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() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map"></div>
</body>
</html>
Values of z-index vary from 100 to 200 in increments of 10, depending on the generation. However I've also tried making them 9100 to 9200, and various other things.
I've seen it suggested that the icons need to have a CSS "position" in order to make z-index work. However I've tried
#map img[src^='/myfamilyroots/images'] {position:relative!important;}
and many variations on that theme without success.
This driving me mad. As far as I can see I have followed the Google Maps reference guide, yet nothing I do will change the way the markers are displayed.
zIndex is expected to be of type Number, but getAttribute() always returns strings.
Convert the string into a Number before you assign the zIndex
var z_index = Number(markers[i].getAttribute("z_index"));

Upgrading dual map program from Google Maps apiV2 to apiV3

I have a Google map API V2 script allowing two maps of different sizes and zoom levels to move together, when one map is panned the other also moves to maintain the same center point. The smaller map has a Xhair in the center that returns to the center after it has been panned, the larger map has multiple markers.
I'm trying to upgrade the code to API V3, but the V3 maps aren't moving each other and the smaller map Xhair isn't functioning. Can someone please tell me what am I missing in the script upgrade from API V2 to API V3?
V2 code:
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
function createMarker(point) {
map.addOverlay(new GMarker(point));
}
// ===== Setup The Maps =====
// Display the main map, with some controls and set the initial location
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(54.531283,-125.125537), 12);
// Set up three markers on the main map
createMarker(new GLatLng(54.207882,-125.661621));
createMarker(new GLatLng(49.214790,-124.054399));
createMarker(new GLatLng(49.053632,-122.352859));
// create the crosshair icon, which will indicate where we are on the minimap
// Lets not bother with a shadow
var Icon = new GIcon();
Icon.image = "xhair.png";
Icon.iconSize = new GSize(21, 21);
Icon.shadowSize = new GSize(0,0);
Icon.iconAnchor = new GPoint(11, 11);
Icon.infoWindowAnchor = new GPoint(11, 11);
Icon.infoShadowAnchor = new GPoint(11, 11);
// Create the minimap
var minimap = new GMap2(document.getElementById("minimap"));
minimap.setCenter(new GLatLng(54.531283,-125.125537), 7);
// Add the crosshair marker at the centre of the minimap and keep a reference to it
var xhair = new GMarker(minimap.getCenter(), Icon);
minimap.addOverlay(xhair);
// ====== Handle the Map movements ======
// Variables that log whether we are currently causing the maps to be moved
var map_moving = 0;
var minimap_moving = 0;
// This function handles what happens when the main map moves
// If we arent moving it (i.e. if the user is moving it) move the minimap to match
// and reposition the crosshair back to the centre
function Move(){
minimap_moving = true;
if (map_moving == false) {
minimap.setCenter(map.getCenter());
xhair.setPoint(map.getCenter());
xhair.redraw(true);
}
minimap_moving = false;
}
// This function handles what happens when the mini map moves
// If we arent moving it (i.e. if the user is moving it) move the main map to match
// and reposition the crosshair back to the centre
function MMove(){
map_moving = true;
if (minimap_moving == false) {
map.setCenter(minimap.getCenter());
xhair.setPoint(minimap.getCenter());
xhair.redraw(true);
}
map_moving = false;
}
// Listen for when the user moves either map
GEvent.addListener(map, 'move', Move);
GEvent.addListener(minimap, 'moveend', MMove);
}
// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
Non-working V3 code:
<script type="text/javascript">
function createMarker(point) {
map.addOverlay(new google.maps.Marker(point));
}
// ===== Setup The Maps =====
// Display the main map, with some controls and set the initial location function initialize() {
var map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Set up three markers on the main map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(54.207882,-125.661621),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.214790,-124.054399),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.053632,-122.352859),
map: map
});
// create the crosshair icon, which will indicate where we are on the minimap
// Lets not bother with a shadow
var Icon = new google.maps.MarkerImage();
Icon.image = "xhair.png";
Icon.iconSize = new google.maps.Size(21, 21);
Icon.shadowSize = new google.maps.Size(0,0);
Icon.iconAnchor = new google.maps.Point(11, 11);
Icon.infoWindowAnchor = new google.maps.Point(11, 11);
Icon.infoShadowAnchor = new google.maps.Point(11, 11);
// Create the minimap
var minimap = new google.maps.Map(
document.getElementById('minimap'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Add the crosshair marker at the centre of the minimap and keep a reference to it
var xhair = new google.maps.Marker(minimap.getCenter(), Icon);
minimap.addOverlay(xhair);
// ====== Handle the Map movements ======
// Variables that log whether we are currently causing the maps to be moved
var map_moving = 0;
var minimap_moving = 0;
// This function handles what happens when the main map moves
// If we arent moving it (i.e. if the user is moving it) move the minimap to match
// and reposition the crosshair back to the centre
function Move(){
minimap_moving = true;
if (map_moving == false) {
minimap.setCenter(map.getCenter());
xhair.setPoint(map.getCenter());
xhair.redraw(true);
}
minimap_moving = false;
}
// This function handles what happens when the mini map moves
// If we arent moving it (i.e. if the user is moving it) move the main map to match
// and reposition the crosshair back to the centre
function MMove(){
map_moving = true;
if (minimap_moving == false) {
map.setCenter(minimap.getCenter());
xhair.setPoint(minimap.getCenter());
xhair.redraw(true);
}
map_moving = false;
}
// Listen for when the user moves either map
google.maps.event.addListener(map, 'move', Move);
google.maps.event.addListener(minimap, 'moveend', MMove);
// google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', initialize);
The upgrade guide seems to have little information on Events, some obsolete events don't seem to be listed in the obsolete code. The V2 events: "move" and "moveend" are apparently not supported in V3, however there are similar (but not the same) V3 events; dragstart, drag, dragend, and center_changed. Since the drag events aren't compatable with additional selection buttons I'm using: I went with center_changed which works like a charm for my application.
I explored a few options for the center cross hair, but they seemed to have dead spots or jumped around when the maps were panned, so I eliminated the javascript solutions and went with a simple solution from Drew Noakes.
This is what I came up with to fix the non-working V3 code, might help someone out there.
V3 code:
<script type="text/javascript">
// ===== Setup The Maps =====
// Display the main map and set the initial location
var map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 12,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Set up the three markers on the main map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(54.207882,-125.661621),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.214790,-124.054399),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.053632,-122.352859),
map: map
});
// Create the minimap
var minimap = new google.maps.Map(
document.getElementById('minimap'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 7,
zoomControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Add the crosshair marker at the centre of the minimap using html and CSS
// ====== Handle the Map movements ======
// Variables that log whether we are currently causing the maps to be moved
var map_moving = 0;
var minimap_moving = 0;
// This function handles what happens when the main map moves
// If we arent moving it (i.e. if the user is moving it) move the minimap to match
google.maps.event.addListener(map, 'center_changed', function(){
minimap_moving = true;
if (map_moving == false) {
minimap.setCenter(map.getCenter());
}
minimap_moving = false;
})
// This function handles what happens when the mini map moves
// If we arent moving it (i.e. if the user is moving it) move the main map to match
google.maps.event.addListener(minimap, 'center_changed', function(){
map_moving = true;
if (minimap_moving == false) {
map.setCenter(minimap.getCenter());
}
map_moving = false;
})
// google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', initialize);
</script>
//The HTML:
<div id="map" style="width:627px; height: 627px"></div>
<div id="container">
<div id="minimap" style="width:370px; height:370px;"></div>
<div id="xhair"><img src="../images/xhair.png" width="20" height="20" /></div>
</div>
//The CSS:
#container { position:relative; }
#map { height:100%; width:100%; }
#xhair {
position:absolute;
left:47%;
top:47%;
}

markerclusterer limits

Hi this is my first post here..
I have been playing around with google maps trying to make a list of campsites in France.
I have got to the point of reading an xml file of the data
Loading the map and clustering the results and it all works but very slow.
Q1 Is there a limit on the number of markers you can render even using the clusterer (there are >7000 records at the moment)
Q2
Is there anything obviously wrong with the code I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Read XML in Microsoft Browsers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false&language=en&region=GB" type="text/javascript"></script>
<script src="scripts/markerclusterer.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="stylesheets/style_1024.css" />
<script type="text/javascript">
var xmlDoc;
function loadxml() {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.onreadystatechange = readXML;
xmlDoc.load("xml_files/France_all.xml");
}
function readXML() {
if (xmlDoc.readyState == 4) {
//alert("Loaded");
//set up map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(0, 0),
mapTypeControl: true,
mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({ maxWidth: 100 });
var marker, i
var markers = [];
var html = [];
var x = (xmlDoc.getElementsByTagName("placemark").length);
//for (i = 0; i < x; i++) {
for (i = 0; i < x; i++) {
//document.write(xmlDoc.documentElement.childNodes[1].firstChild.tagName) + '<br>';
desc = xmlDoc.getElementsByTagName("description")[i].text;
lat = parseFloat((xmlDoc.getElementsByTagName("latitude")[i].text));
lon = parseFloat((xmlDoc.getElementsByTagName("longitude")[i].text));
myicon = (xmlDoc.getElementsByTagName("icon")[i].text);
//create new point
var point = new google.maps.LatLng(lat, lon);
//create new marker
marker = new google.maps.Marker({
position: point,
panControl: false,
map: map,
icon: myicon
});
//increae map bounds
bounds.extend(point);
//fit to bounds
map.fitBounds(bounds);
//add reference to arrays
markers.push(marker);
html.push(desc);
//add listener
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(html[i]);
infowindow.open(map, marker);
}
})(marker, i));
//alert(i + " " + desc +" added!");
};
//var mc = new MarkerClusterer(map);
var mcOptions = {gridSize: 50, maxZoom: 15 };
var mc = new MarkerClusterer(map, markers, mcOptions);
}
}
</script>
</head>
<body onload="loadxml()">
<div style="height:100%; width:100%">
<div id="map" style="float:left; width:50%; height:100%">
<!--filled via script-->
</div>
<div style="float:left; width:50%; height:100%">
<h4>Select Region</h4>
<select>
<option value="Alsace" onclick="loadxml()">Alsace</option>
</select>
</div>
</div>
</body>
</html>
This article may help. A tile based solution (FusionTables, KmlLayer, or a server based custom map) will render more quickly than native Google Maps API v3 objects, even with clustering. You may be seeing the transfer and processing time of the xml file.

Google Map V3 API Not working in localhost

I copied following javascript code from google maps documentation, but it doesn't work, it only shows a white blank page, nothing loads.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: http://code.google.com/apis/maps/documentation/javascript/basics.html#SpecifyingSensor
-->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Since v3 require api key what's wrong with it? I checked in google chrome and firefox but no clue.
Looks like you are missing a closing html tag, unless that is a typo.
Add this </html> at the bottom of the page.
You need to provide a center location to create your map. In your initialize() function change the map options to include the location you want to start with:
var myCenter = new google.maps.LatLng(60.0,105.0);
var myOptions = {
zoom: 6,
center: myCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
When (or if) you get a location from the geolocation service the center will be changed by your code.
Old question, will answer anyhow in case anyone else lands here.
I ended up using a slightly different implementation to get this to work:
<script type="text/javascript">
function initialize() {
var mapOptions = {zoom: 8, center: new google.maps.LatLng(-34.397, 150.644)};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp'+
'&key={{API_KEY}}&sensor=false&callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript();
</script>
The part that I had to add to get it to work from other (nearly identical) versions of this, was the () at the end of loadScript(). The implicit function call simply was not happening.
You will need to replace {{API_KEY}} with your own. I am not sure if this is required, but it was part of what led me to a working implementation.
If you do not have one, follow the steps listed here

Resources