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"));
Related
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!
Im triying to create a map with a marker from a position taken from a database. I succeed creating the map using this tutorial. The problem is that i have to enter manually the center position when i create the map.
¿Is there a way to center the map using the marker?. The code that im using is the following:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("loadposition.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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitud")),
parseFloat(markers[i].getAttribute("Longitud")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
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() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
Also my XML generated file looks like this:
<markers>
<marker Latitud="-33.449148" Longitud="-70.552886"/>
</markers>
Thanks a lot!
I used this in an app after adding the marker. Might help you.
bounds = new google.maps.LatLngBounds();
bounds.extend(marker.position);
if (!bounds.isEmpty())
map.panTo(bounds.getCenter());
Original idea was to find the center of a bunch of markers, so this might be overkill.
To reproduce, download CefSharp from here:
https://github.com/cefsharp/CefSharp
And run the CefSharp.WinForms.Example
Now run my fiddle on your browser and the CefSharp browser:
http://jsfiddle.net/bjmL9/
I added an alert displaying full address data on click (street_number, route, neighborhood, locality, administrative_area_level_2, administrative_area_level_1, country, postal_code).
Compare the data displayed on your browser to the one on the CefSharp browser.
The problem:
In my browser, the locality shows as "Culiacán Rosales", but on the Cef browser it gets truncated to "Culiacán". The country behaves weird too with Cef displaying "Mexico" instead of "México" (unaccented).
I am on the edge of quitting cef cuz i can't get a google match on this problem and no idea how to fix it...
This is the code of the fiddle since it won't last for ever:
<!DOCTYPE html>
<html>
<head>
<title>Google Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link href="MapStyle.css" rel="stylesheet" type="text/css" media="all"/>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
var map;
var geocoder;
function initialize() {
var placeMarkers = [];
geocoder = new google.maps.Geocoder();
var aquamiller = new google.maps.LatLng(
24.832956,
-107.389775);
var mapOptions = {
zoom: 16,
center: aquamiller,
};
map = new google.maps.Map(
document.getElementById('map-canvas'),
mapOptions);
createSearchBar(map, placeMarkers);
google.maps.event.addListener(
map,
'click',
function(e) {
getAddress(e.latLng, function(address) {
alert(
address.street_number + ', ' +
address.route + ', ' +
address.neighborhood + ', ' +
address.locality + ', ' +
address.administrative_area_level_2 + ', ' +
address.administrative_area_level_1 + ', ' +
address.country + ', ' +
address.postal_code);
});
});
}
function getAddress(latLng, callBack)
{
geocoder.geocode({'latLng': latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = {};
var components = results[0].address_components;
for (var i = 0 ; i< components.length ; i++) {
address[components[i].types[0]] = components[i].long_name;
}
callBack(address);
}
else {
alert('No results found');
}
}
else {
alert('Geocoder failed due to: ' + status);
}
});
}
function createSearchBar(map, markers)
{
var input = /** #type {HTMLInputElement} */(document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(/** #type {HTMLInputElement} */(input));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
console.log(places);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
console.log(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(16);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
</body>
</html>
Hey wait once more I see the same behavior (missing " Rosales" and accent in "México") with both my standard Chrome 35 and IE 10.
So, maybe it's related to a missing CEF language pack: https://github.com/cefsharp/cef-binary/tree/cef_binary_1.1364.1123/Release/locales .. the NuGet you use probably only has en-US.pak
... Tested a bit more with your fiddle example. Dropping es.pak in my install didn't help. BUT I see similar if I search for "Sønderborg, Denmark" in the search box in the map. (At some locations there it says "S**o**nderborg", no "ø" ) So are you sure its browser related and not just the google API?
update Asking with language=es as in:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&language=es&libraries=places"></script>
Alters the response from googles API. Currently verified using my iPad and your fiddle!
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®ion=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.
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.