<script type='text/javascript'>
jQuery(document).ready(function($){
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
var encodedString;
var stringArray = [];
encodedString = document.getElementById("encodedString").value;
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `table-name`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'><b>Lat:</b> ".$row[1].
"<br><b>Long:</b> ".$row[2].
"<br><b>Name: </b>".$row[3].
"<br><b>Address: </b>".$row[4].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
I have used above code for google map location from MySQL database.
Above code fetch lat, Lang from MySQL database and dynamically create google map.
When I run above code It gave me error like that:
There are two errors named too much recursion & initMap is not function.
Can anybody help me to sort out it.
Thanks in advance.
You have not defined initMap in your js file. That's why you are getting that error. You probably need to remove the callback part from the google map api script
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" async defer></script>
Also check if the lat and lon contain valid numeric values in the following statement
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
This is probably a simple issue but I would appreciate any help
I have loaded a $_SESSION variable from my MVC model , its a multidimensional area of latitude and longitude points in a map. here where I loaded this from
for($i=0; $i<count($markets['results']); $i++) {
.
.
$marketinfo["lat"][$i] = floatval($lat);
$marketinfo["long"][$i] = floatval($lon);
};
$_SESSION['MARKETLOCATION']['LAT'] = $marketinfo["lat"];
$_SESSION['MARKETLOCATION']['LONG'] = $marketinfo["long"];
Then down in the view section I am calling a _template for header with this code
<script type="text/javascript">
function createmap(LatLong) {
var firstpass = true;
for (var i = 0; i < $LatLong.length; i++) {
var lat = $LatLong['LAT'][i];
var lng = $LatLong['LONG'][i];
if (firstpass === true){
var map = new google.maps.Map(document.getElementById('map-canvas'),{
zoom: 10,
center: new google.maps.LatLng($lat[0]+','+$lng[0]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
firstpass = false;
}
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
position: new google.maps.LatLng($lat[i]+','+$lng[i]),
map: map
});
}
window.onload=function(){("createmap($_SESSION['MARKETLOCATION']");};
}
</script>
</head>
<body>
<div class='Mapbox' id = 'map-canvas' ></div>
Problem is the map is not displaying at all. I know that my API key is correct because I tested it before I created this code. So I think it probibaly has to do with Passing the session variable
Again any insight would be appreciated
Javascript and php are two different languages. You need to output your variable from php but you cannot just echo it as $_SESSION['MARKETLOCATION'] is an array.
You should do something like:
var session_variable = <?php echo json_encode($_SESSION['MARKETLOCATION']); ?>;
// now you might have to do some processing on session_variable like parsing it...
// for an example:
var session_object = JSON.parse(session_variable);
window.onload=function(){ createmap(session_object); };
Fix you code:
window.onload=function(){("createmap(<?php echo $_SESSION['MARKETLOCATION'] ?>");};
I need to implement a custom info window on my google map.
I found this custom info window here : Creating custom info windows in Google Maps
I used the code provided by Googles Developers page , to create the map and everything worked great with the typical info window. Now i changed my code to try and implement the above custom info window , called "infobox" . However it is not working. I am not sure if i used the code correctly.
This is my code for the google map. Note the infoBox function , is the custom info window.
<!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 and Google Maps Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 15,
mapTypeId: 'roadmap'
});
//var infoWindow = new google.maps.InfoWindow;
infobox = new InfoBox({ width: "260px" }); // initialize
// Change this depending on the name of your PHP file
downloadUrl("testing.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("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infobox, html);
}
});
}
function bindInfoWindow(marker, map, infobox, html) {
google.maps.event.addListener(marker, 'click', function() {
//infoWindow.setContent(html);
//infoWindow.open(map, marker);
infobox.setContent(html); // set content
infobox.open(map, marker); // open on the marker
infobox.draw(); // to redraw if infobox size changed
//infobox.close();
});
}
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 InfoBox(opt_opts) {
opt_opts = opt_opts || {};
this.imgPath='img/infoBox/';
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
this.content_ = opt_opts.content || "";
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
this.boxStyle_ = opt_opts || {};
this.infoBoxClearance_ = new google.maps.Size(1, 1);
this.isHidden_ = opt_opts.isHidden || false;
this.pane_ = "overlayMouseTarget";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.eventListener1_ = null;
this.eventListener2_ = null;
this.eventListener3_ = null;
this.contextListener_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3. */
InfoBox.prototype = new google.maps.OverlayView();
// Creates the DIV representing the InfoBox. #private
InfoBox.prototype.createInfoBoxDiv_ = function(){
var bw, me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
var cancelHandler = function (e){ e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); };
// This handler ignores the current event in the InfoBox and conditionally prevents the event from being passed on to the map. It is used for the contextmenu event.
var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) e.preventDefault(); if (!me.enableEventPropagation_){ e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } };
if (!this.div_){ // first time create
this.div_ = document.createElement("div");
this.div_.className = 'infowindow';
this.setBoxStyle_();
// Apply required styles:
if (this.zIndex_ !== null) this.div_.style.zIndex = this.zIndex_;
this.div_.contentDiv = document.createElement('div');
this.div_.contentDiv.className = 'infowindow-wrapper';
this.div_.contentDiv.innerHTML = this.content_;
this.div_.innerHTML = '<img src="'+this.imgPath+'close.png" align="right" class="infowindow-close">';
this.div_.appendChild(this.div_.contentDiv);
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) this.fixedWidthSet_ = true;
else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.fixedWidthSet_ = true;
}
else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
//add shadow
this.shadowContainer_ = document.createElement("div");
this.shadowContainer_.style.position='absolute';
this.shadowContainer_.style.display = 'block';
this.shadowContainer_.style.zIndex='-99';
this.getPanes()['overlayShadow'].appendChild(this.shadowContainer_);
this.shadow = document.createElement('img');
this.shadow.src = this.imgPath+'shadow.png';
this.shadow.style.position='absolute';
this.shadow.style.width = '100%';
this.shadow.style.height = '100%';
this.shadowContainer_.appendChild(this.shadow);
if (!this.enableEventPropagation_) {
this.eventListener1_ = google.maps.event.addDomListener(this.div_.contentDiv, "mousedown", cancelHandler);
this.eventListener2_ = google.maps.event.addDomListener(this.div_, "click", function(e){
e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation();
if (GoogleMap && GoogleMap.closeEditors) GoogleMap.closeEditors(true);
});
//this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", cancelHandler);
try{ this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", facilityEditor);}catch(e){}
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
var contentWidth = parseInt(this.div_.style.width.slice(0,-2)), contentHeight = this.div_.offsetHeight;
this.wrapperParts = { //create an object to reference each image
tl:{l:-26, t:-26, w:26, h:26},
t:{l:0, t:-26, w:contentWidth, h:26},
tr:{l:contentWidth, t:-26, w:26, h:26},
l:{l:-26, t:0, w:26, h:contentHeight},
r:{l:contentWidth, t:0, w:26, h: contentHeight },
bl:{l:-26, t:contentHeight, w:26, h:26},
b:{l:0, t:contentHeight, w:contentWidth, h:26},
br:{l:contentWidth, t:contentHeight, w:26, h:26},
p:{l:contentWidth-170, t:contentHeight+18, w:92, h:77 }
}
for (i in this.wrapperParts){ //create the image DOM objects
var img = document.createElement('img');
img.src = this.imgPath + i + '.png'; //load the image from your local image directory based on the property name of the wrapperParts object
img.style.position='absolute'; //set the appropriate positioning attributes
img.style.top=this.wrapperParts[i].t+'px';
img.style.left=this.wrapperParts[i].l+'px';
img.style.width=this.wrapperParts[i].w+'px';
img.style.height=this.wrapperParts[i].h+'px';
this.div_.appendChild(img);
this.wrapperParts[i].img = img;
}
google.maps.event.trigger(this, "domready");
}
else {
var contentWidth = parseInt(this.div_.style.width.slice(0,-2)), contentHeight = this.div_.offsetHeight, twp=this.wrapperParts;
twp.t.img.style.width=contentWidth+'px';
twp.tr.img.style.left=contentWidth+'px';
twp.l.img.style.height=contentHeight+'px';
twp.r.img.style.left=contentWidth+'px';
twp.r.img.style.height=contentHeight+'px';
twp.bl.img.style.top=contentHeight+'px';
twp.b.img.style.top=contentHeight+'px';
twp.b.img.style.width=contentWidth+'px';
twp.br.img.style.left=contentWidth+'px';
twp.br.img.style.top=contentHeight+'px';
twp.p.img.style.left=(contentWidth-170)+'px';
twp.p.img.style.top=(contentHeight+18)+'px';
}
};
InfoBox.prototype.addClickHandler_=function(){
this.closeListener_ = google.maps.event.addDomListener(this.div_.firstChild, 'click', this.getCloseClickHandler_());
try{ this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", facilityEditor);}catch(e){}
};
InfoBox.prototype.getCloseClickHandler_=function () { var me = this; return function(){ me.close(); google.maps.event.trigger(me, "closeclick"); }; };
//Pans the map so that the InfoBox appears entirely within the map's visible area. #private
InfoBox.prototype.panBox_ = function (disablePan) {
if (!disablePan) {
var map = this.getMap();
var bounds = map.getBounds();
// The degrees per pixel
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var boundsSpan = bounds.toSpan();
var longSpan = boundsSpan.lng();
var latSpan = boundsSpan.lat();
var degPixelX = longSpan / mapWidth;
var degPixelY = latSpan / mapHeight;
// The bounds of the map
var mapWestLng = bounds.getSouthWest().lng();
var mapEastLng = bounds.getNorthEast().lng();
var mapNorthLat = bounds.getNorthEast().lat();
var mapSouthLat = bounds.getSouthWest().lat();
// The bounds of the box
var position = this.position_;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var iwWestLng = position.lng() + (iwOffsetX - padX - this.div_.contentDiv.offsetWidth/2 - 450) * degPixelX; // 450 - move right - from under the sidebar
var iwEastLng = position.lng() + (iwOffsetX + padX + 220) * degPixelX;
var iwNorthLat = position.lat() - (iwOffsetY - padY - this.div_.contentDiv.offsetHeight - 180) * degPixelY; // 180 - move down - from under the top search bar
var iwSouthLat = position.lat() - (iwOffsetY + padY + 20) * degPixelY;
// Calculate center shift
var shiftLng = (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) + (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
var shiftLat = (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) + (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);
if (!(shiftLat === 0 && shiftLng === 0)) {
// Move the map to the new shifted center.
var c = map.getCenter();
map.setCenter(new google.maps.LatLng(c.lat() - shiftLat, c.lng() - shiftLng));
}
}
};
// Sets the style of the InfoBox. #private
InfoBox.prototype.setBoxStyle_ = function () {
var i;
var boxStyle = this.boxStyle_;
for (i in boxStyle) if (boxStyle.hasOwnProperty(i)) this.div_.style[i] = boxStyle[i];
// Fix up opacity style for benefit of MSIE:
if (typeof this.div_.style.opacity !== "undefined") this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
};
// Get the widths of the borders of the InfoBox. #private; #return {Object} widths object (top, bottom left, right)
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
}
else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
// Invoked when <tt>close</tt> is called. Do not call it directly.
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.shadowContainer_.parentNode.removeChild(this.shadowContainer_);
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
//Draws the InfoBox based on the current map projection and zoom level.
InfoBox.prototype.draw = function(){
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x - this.div_.offsetWidth + 180 ) + "px";
this.div_.style.top = (pixPosition.y - this.div_.offsetHeight - 125) + "px";
this.shadowContainer_.style.left = (pixPosition.x - this.div_.offsetWidth + 220 ) + 'px';
this.shadowContainer_.style.top = (pixPosition.y - this.div_.offsetHeight - 130) + "px";
this.shadowContainer_.style.height = (this.div_.offsetHeight+100 ) + 'px';
this.shadowContainer_.style.width = (this.div_.offsetWidth+100 ) + 'px';
if (this.isHidden_) this.div_.style.visibility = 'hidden';
else this.div_.style.visibility = "visible";
this.panBox_();
};
InfoBox.prototype.setContent = function(content){
this.content_ = content;
if (this.div_){// Odd code required to make things work with MSIE.
this.div_.style.visibility='hidden'
if (!this.fixedWidthSet_) this.div_.style.width = "";
this.div_.contentDiv.innerHTML = content;
// Perverse code required to make things work with MSIE. (Ensures the close box does, in fact, float to the right.)
if (!this.fixedWidthSet_){ this.div_.style.width = this.div_.offsetWidth + "px"; this.div_.contentDiv.innerHTML = content; }
this.addClickHandler_();
}
// This event is fired when the content of the InfoBox changes. #name InfoBox#content_changed; #event
google.maps.event.trigger(this, "content_changed");
};
//Sets the geographic location of the InfoBox. #param {LatLng} latlng
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) this.draw();
//This event is fired when the position of the InfoBox changes. #name InfoBox#position_changed; #event
google.maps.event.trigger(this, "position_changed");
};
InfoBox.prototype.getContent = function () { return this.content_; }; //Returns the content of the InfoBox. #returns {string}
InfoBox.prototype.show = function (){ this.isHidden_ = false; this.div_.style.visibility = "visible"; }; //Shows the InfoBox.
InfoBox.prototype.hide = function (){ this.isHidden_ = true; this.div_.style.visibility = "hidden"; }; //Hides the InfoBox.
InfoBox.prototype.open = function (map, anchor) {
if (anchor) this.position_ = anchor.getPosition();
this.setMap(map);
};
//Removes the InfoBox from the map.
InfoBox.prototype.close = function (){
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 100%; height: 600px"></div>
</body>
</html>
In the above code , i just changed everything mentioning infowindow , with the new infobox , and added the new function InfoBox(). However i am not sure , how and where i should use the
infobox.setContent(html); // set content
infobox.open(map, marker); // open on the marker
infobox.draw(); // to redraw if infobox size changed
infobox.close();
Where should i use the infobox.close() function? In my code i commented this line , cause i didnt know how to use it.
I believe your missing a position: absolute style for the infobox and also background color if it's not set in the css (originally I had that set in css, that's why it worked for me :-))
look for this line in your code:
this.div_.className = 'infowindow';
and add this below:
this.div_.style.position = 'absolute';
this.div_.style.backgroundColor = '#fff';
You should also add some images for the infobox as the whole box is build based on the images (you'll find references in the script).
I have been trying to make a Google map which would show multiple markers on different locations. This map is connected to a database where it stores the latitude and longitude. I want to make this map so that I can change the latitude and longitude in the database so that the markers can update and relocate to the new location. But I do not want the whole map to reload, just the data. Here is the code, and thank you for your help!
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'mm_20_blue.png';
iconBlue.shadow = 'mm_20_shadow.png';
iconBlue.iconSize = new GSize(16, 25);
iconBlue.shadowSize = new GSize(27.5, 25);
iconBlue.iconAnchor = new GPoint(7.5, 25);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'mm_20_red.png';
iconRed.shadow = 'mm_20_shadow.png';
iconRed.iconSize = new GSize(16, 25);
iconRed.shadowSize = new GSize(27.5, 25);
iconRed.iconAnchor = new GPoint(7.5, 25);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["1"] = iconBlue;
customIcons["2"] = iconRed;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setUIToDefault();
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(34.081187, -83.980721), 8);
geocoder = new GClientGeocoder();
GDownloadUrl("genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var Names = markers[i].getAttribute("Names");
var phoneNum = markers[i].getAttribute("phoneNum");
var gender = markers[i].getAttribute("gender");
var homeAd = markers[i].getAttribute("homeAd");
var lat = markers[i].getAttribute("latitudeE6")
var lng = markers[i].getAttribute("longitudeE6")
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitudeE6")),
parseFloat(markers[i].getAttribute("longitudeE6")));
var marker = createMarker(point, Names, phoneNum, gender, homeAd, lat, lng);
map.addOverlay(marker);
}
}
);
}
}
function createMarker(point, Names, phoneNum, gender, homeAd, lat, lng) {
var marker = new GMarker(point, customIcons[gender]);
place = marker
var html = "<b>Name: " + Names + "</b> <br/>Phone #: " + phoneNum + "</b> <br/>Home Address: " + homeAd + "</b> <br/>Current Address: " + place.address
+ "</b> <br/>Latitude: " + lat + "</b> <br/>Longitude: " + lng;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
};
//]]>
(some part of the code was excluded, like the MD5 key)
first make function called load_marker
put your code which starting gdownloadurl in new function and load markers when your data change by calling this javascript function. you may need to clear all markers first.
also you may want to reload markers in map event. there are two usefull events you can use.
drag_end and zoom_changed . you can register these by gmap.registerEvent function
edit: added code sample / your code should be like this.
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setUIToDefault();
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(34.081187, -83.980721), 8);
geocoder = new GClientGeocoder();
}
function load_markers() {
/*clear all*/
map.clearOverlays();
GDownloadUrl("genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var Names = markers[i].getAttribute("Names");
var phoneNum = markers[i].getAttribute("phoneNum");
var gender = markers[i].getAttribute("gender");
var homeAd = markers[i].getAttribute("homeAd");
var lat = markers[i].getAttribute("latitudeE6")
var lng = markers[i].getAttribute("longitudeE6")
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitudeE6")),
parseFloat(markers[i].getAttribute("longitudeE6")));
var marker = createMarker(point, Names, phoneNum, gender, homeAd, lat, lng);
map.addOverlay(marker);
}
}
);
}
}
You should switch to Google Maps API v3, where pointers are linked to the map and not the opposite. Plus you'll get a bunch of interesting new features for free!
This is weird. I'm using the marker clusterer to bunch all my markers however the first time when the map renders and when I try to drag it or pan it - it hangs and firefox tells me the script is slowing it down so I have to stop the script. But if I zoom it out - it zooms normally and panning it from then on causes no issues - I have no idea whats going wrong here. Here is my code am I missing something here - must be something wrong with my initialisation:
var map = null;
function initializeGMaps() {
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map_canvas"));
{
var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var i = 0;
iconBlue = new GIcon();
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var marker = new GMarker(point,{ icon:iconBlue, });
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '<\/a><br>';
i++;
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
// create the map
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng( 43.907787, -50.359741), 5);
var customUI = map.getDefaultUI();
customUI.controls.maptypecontrol = false;
customUI.controls.menumaptypecontrol = true;
map.setUI(customUI);
// A function to read the data
function readMap() {
var url='get-map-markers.php';
var request = GXmlHttp.create();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = request.responseXML;
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
// hide the info window, otherwise it still stays open where the removed marker used to be
map.getInfoWindow().hide();
map.clearOverlays();
// empty the array
allmarkers = [];
//var clusterer = new Clusterer( map );
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
//map.addOverlay(marker);
allmarkers.push(marker);
//clusterer.AddMarker( marker, html );
}
var markerCluster = new MarkerClusterer(map, allmarkers);
// put the assembled side_bar_html contents into the side_bar div
}
}
request.send(null);
}
readMap();
}
}
}
$(document).ready(function() { initializeGMaps(); } );
$('body').unload( function () { GUnload(); } );
UPDATE: I just noticed that the script at google.com is causing the page to be slow :( how do I fix this? WHat have I done in my code to bring this behavior.
Markerclusterer sucks. Use this one:
http://googlemapsapi.martinpearman.co.uk/clustermarker
My demo: http://www.stopdetelefoongids.nl/stats/ (source in /includes/maps.js )