I'm having a problem with my info window of my markers in my google maps. The markers show correctly but whenever you click on a marker it only shows the last marker set's info(above the last marker). Here is my code:
<?php
//Open connection to database to fetch markers from maps table:
require_once("config.php"); // get config
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); // connect to db
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("drpayne_test", $con); // select db
$q = "SELECT * FROM maps"; // form query
$result = mysql_query($q); // run query
// output the start of the HTML Map Page
echo <<<END
<!DOCTYPE html>
<html>
<head>
<title>Marker database viewer</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var marker=new Array();
var infowindow=new Array();
function initialize() {
var contentString;
var mylatlng;
var latlng = new google.maps.LatLng(34.52867,-83.98645);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
END;
// loop through the rows of map markers
while($row = mysql_fetch_array($result))
echo <<<END
// Marker Code Start
contentString = "<h1> {$row['title']} </h1><p> {$row['descr']} </p>";
mylatlng = new google.maps.LatLng({$row['lat']},{$row['lng']});
infowindow[{$row['id']}] = new google.maps.InfoWindow({
content: contentString
});
marker[{$row['id']}] = new google.maps.Marker({
position: mylatlng,
map: map,
title:" {$row['geo']} "
});
google.maps.event.addListener(marker[{$row['id']}], 'click', function() {
infowindow[{$row['id']}].open(map,marker[{$row['id']}]);
});
// Marker Code End
END;
// Output the end of the HTML page
echo <<<END
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
END;
?>
You have a closure problem, I had the same problem some times ago and I get an answer here
Just adapt it to your case
Related
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!
So I have a list of baseball teams I want to map that each have a custom icon and text window. Since my primary zoom level is at 4, most of the icons, especially in the northeast are very congested.
part of the code is below, sorry for the length. It's what I know to do right now. Had tried adding the markercluster variable, but wasn't sure how to add each team into it, that or make multiple clusters based on the teams I am having issues with.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBblZOVoLgeHeWlv_zt5dR6dlQbRHMUPKo&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.8282, -98.5795),
zoom: 4
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var padres = 'http://s7d2.scene7.com/is/image/Fathead/lgo_mlb_san_diego_padres?layer=comp&fit=constrain&hei=50&wid=200&fmt=png-alpha&qlt=95,0&op_sharpen=1&resMode=bicub&op_usm=0.0,0.0,0,0&iccEmbed=0';
var padresLatLng = new google.maps.LatLng(32.7073, -117.1566);
var padresmarker = new google.maps.Marker({
position: padresLatLng,
map: map,
icon: padres,
title: 'San Diego Padres'
});
var padresString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">San Diego Padres</h1>'+
'<div id="bodyContent">'+
'</div>'+
'</div>';
var padreswindow= new google.maps.InfoWindow({
content: padresString
});
google.maps.event.addListener(padresmarker, 'click', function() {
padreswindow.open(map, padresmarker);
});
var dodgers = 'http://i.cdn.turner.com/si/.element/img/4.0/global/baseball/mlb/logos/dodgers_50.png';
var dodgersLatLng = new google.maps.LatLng(34.0736, -118.2400);
var dodgersmarker = new google.maps.Marker({
position: dodgersLatLng,
map: map,
icon: dodgers,
title: 'Los Angeles Dodgers'
});
var dodgersString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Los Angeles Dodgers</h1>'+
'<div id="bodyContent">'+
'</div>'+
'</div>';
var dodgerswindow= new google.maps.InfoWindow({
content: dodgersString
});
google.maps.event.addListener(dodgersmarker, 'click', function() {
dodgerswindow.open(map, dodgersmarker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
As minimum you have to include markerclusterer.js library and to add
var mc = new MarkerClusterer(map, [dodgersmarker, padresmarker]);
at the end of initialize() function. Marker Clusterer expects as parameters a map, an array of markers and options as optional parameters.
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 am using google-maps-utility-library-v3.
I am trying to zoom in and zoom out, if the dot is not in screen anymore, I want to see count 0.
But it doesn't work. If I comment out mgr.addMarkers(markers,5); It works.... But it will always be 0 because no maker is managed by the manager.
Could someone tell me why?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=??????????????&sensor=false">
</script>
<script type="text/javascript" src="downloadxml.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js"></script>
<script type="text/javascript">
var map = null;
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(42.35428, -71.05525),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), myOptions);
//hard code a marker
var lat = 42.35428;
var lng = -71.05525;
var point = new google.maps.LatLng(lat,lng);
var html = "I am a hard-coded dot";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: "http://www.google.com/mapfiles/arrow.png",
shadow: "http://www.google.com/mapfiles/arrowshadow.png"
});
var markers = [];
markers.push(marker);
var mgr = new MarkerManager(map);
mgr.addMarkers(markers,5);
mgr.refresh();
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoomLevel = map.getZoom();
var count = mgr.getMarkerCount(zoomLevel);
document.getElementById("Listing").innerHTML += count + "<BR>";
});
}
</script>
You appear to be using the MarkerManager before it is fully initialized. Here's an updated section of your code to fix the issue:
var markers = [];
markers.push(marker);
var mgr = new MarkerManager(map);
google.maps.event.addListenerOnce(mgr, 'loaded', function(){
mgr.addMarkers(markers, 5);
mgr.refresh();
});
See this example as reference: http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/docs/examples.html