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!
Related
<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]);
i am using google map api to show addresses on map with markers, the problem i am having is, In the marker, i am showing a link to go to the profile page of person which is there in the map, but if there are more than 1 person exists on same address then google group those addresses and doesn't show the link, is there any way we can stop grouping of addresses?
Any help would be appreciated.Thanks
<pre>
<script type="text/javascript">
var global =0;
//<![CDATA[
if (GBrowserIsCompatible()) {
var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var i = 0;
var allIcon = new GIcon();
allIcon.image = "images/icons/<?php echo $map_category; ?>-all.png";
allIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
allIcon.iconSize = new GSize(35, 29);
allIcon.shadowSize = new GSize(37, 34);
allIcon.iconAnchor = new GPoint(9, 34);
allIcon.infoWindowAnchor = new GPoint(9, 2);
allIcon.infoShadowAnchor = new GPoint(18, 25);
allIcon.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
allIcon.printImage = "coldmarkerie.gif";
allIcon.mozPrintImage = "coldmarkerff.gif";
// An array of GIcons, to make the selection easier
var icons = [];
icons[0] = allIcon;
icons[1] = planIcon;
icons[2] = specialIcon;
var clusterIcon = new GIcon();
clusterIcon.image = 'images/icons/<?php echo $map_category; ?>-all.png';
clusterIcon.iconSize = new GSize( 30, 51 );
clusterIcon.shadowSize = new GSize( 56, 51 );
clusterIcon.iconAnchor = new GPoint( 13, 34 );
clusterIcon.infoWindowAnchor = new GPoint( 13, 3 );
clusterIcon.infoShadowAnchor = new GPoint( 27, 37 );
// A function to create the marker and set up the event window
function createMarker(point,name,html,cat,id) {
var marker = new GMarker(point,icons[cat]);
GEvent.addListener(marker, "click", function() {
rating_html = CallRating(<?php echo $page_id; ?>,id);
rating_html = decodeURI(rating_html);
marker.openInfoWindowHtml(html);
document.getElementById("rating_html_"+id+"").innerHTML=rating_html;
});
GEvent.addListener(marker, "dragstart", function() {
map.closeInfoWindow();
});
// save the info we need to use later for the side_bar
gmarkers[i] = marker;
htmls[i] = html;
// add a line to the side_bar html
if(i%2==0)
{
var sclass="even";
}
else
{
var sclass="odd";
}
side_bar_html += '<li class="'+sclass+'"><a href="javascript:myclick(' + i + ',' + id + ')" class="map_data mapdata-list">' + name + '<\/a></li>';
global=i;
i++;
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i,id) {
rating_html = CallRating(<?php echo $page_id; ?>,id);
rating_html = decodeURI(rating_html);
gmarkers[i].openInfoWindowHtml(htmls[i]);
document.getElementById("rating_html_"+id+"").innerHTML=rating_html;
}
// create the map
var map = new GMap(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
//map.setMapType(G_SATELLITE_MAP);
map.setCenter(new GLatLng(<?php echo $emp_info['emp_latitude']; ?>, <?php echo $emp_info['emp_longitude']; ?>), 8);
// create the clusterer
var clusterer = new Clusterer(map);
// set the clusterer parameters if you dont like the defaults
clusterer.icon = clusterIcon;
clusterer.maxVisibleMarkers = 100;
clusterer.gridSize = 5;
clusterer.minMarkersPerClusterer = 5;
clusterer.maxLinesPerInfoBox = 6;
var rating_html="";
// Read the data
var request = GXmlHttp.create();
request.open("GET", "xml/<?php echo $org_id.'/emp/'.$emp_id.'/'.$map_category; ?>.xml", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = GXml.parse(request.responseText);
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
var i = 0;
for (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 GPoint(lng,lat);
var town = markers[i].getAttribute("town");
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var cat = markers[i].getAttribute("cat");
var marker = createMarker(point,name,"<a href='<?php echo $url;?>="+id+"' target='_blank' class='map_data'>"+name+"</a><br>"+town+"<div id='rating_html_"+id+"'></div>",cat,id);
// create clusterer object
clusterer.AddMarker(marker,town);
}
// put the assembled side_bar_html contents into the side_bar div
if(side_bar_html=="")
{
document.getElementById("list_html").innerHTML = "<li>No data found! Please try again.</li>";
}
else
{
document.getElementById("list_html").innerHTML = side_bar_html;
gmarkers[global].openInfoWindowHtml(htmls[global]);
map.closeInfoWindow();
}
// Clear the "please wait" message
}
}
request.send(null);
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
//]]>
</script>
</pre>
If you put multiple markers for single point, those will always overlap. It will be interesting to see if anyone can help you. I would suggest, when there are more than one people come under same place/marker, put their details/links on the infoWindow. Don't try to show multiple markers for same point. And if you are desperate enough to show multiple markers, then just change size of your marker-icons, so that they are visible to user even-if overlaps.
It is a good thing that google is showing all the relative address together otherwise if it wont, markers will be hidden by each other and you wont be able to see even how many markers are there on one place.
I have implemented google map in my project . I've set all the required things . I was wondering the control icons not appearing like pan,zoom etc. But still I can zoom ,pan with clicking on a blurred shape instead of the picture buttons . Anybody can address the issue ? .Sorry for my bad english
<script src="//maps.google.com/maps?file=api&v=2&key=key"
type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var latlng = new GLatLng(<?php echo $lattitude?>, <?php echo $longitude?>);
map.setCenter(latlng, 13);
var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.addOverlay(new GMarker(latlng));
var name = "name";
var address = "address";
var type = "bar";
var point = latlng;
var marker = createMarker(point, name, address, iconRed);
map.addOverlay(marker);
}
}
function createMarker(point, name, address, iconRed) {
var marker = new GMarker(point, iconRed);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
You should not be using V2 of the Google Maps API for your app. That version of the API has been deprecated.
Instead you shoule be using V3:
http://goo.gl/YVKfp
On my website I have a form that allows users to register. It asks users to provide their city, state, and country. I also have a map that drops a marker for each user based on a lat/lng that's drawn from that city, state, country combination ($location).
Because I'm not being super specific (as in, I'm not asking for their ACTUAL address), I have a number of users that have the same lat/lng. And this creates a problem when trying to view markers on my map.
Should I use a clustering service? If so, do you have any suggestions?? Like I said, information flows from mySQL database --> XML --> PHP.
If so, it'll be clustered at the most zoomed level (like I said, same lat/lng). As a result, I'm going to need a info window that allows me to select each user at that particular location.
Ideas? Suggestions??? Much appreciated!!!
Jeremy
MarkerClusterer: http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/docs/examples.html
Or by hand (roughly - sample code only!)
var latlng = new google.maps.LatLng(-33.8671390, 151.2071140);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var markers = [];
var newmarkers = [];
for(var j=0; j<5; j++) {
markers.push({lat:-33.8671390, lng:151.2071140, title:'This is marker #' + i });
if(j==0) newmarkers.push(markers[j]);
for(var i=0; i<newmarkers.length; i++) {
if(newmarkers[i].lat == markers[j].lat && newmarkers[i].lng == markers[j].lng) {
newmarkers[i].title += ' AND ' + markers[j].title;
continue;
}
newmarkers.push(markers[j]);
}
}
for(var i=0; i<newmarkers.length; i++) {
var mkr = new google.maps.Marker({
position: new google.maps.LatLng(newmarkers[i].lat, newmarkers[i].lng),
map: map,
title: newmarkers[i].title
});
}
Thought I'd paste my code:
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 2);
map.enableScrollWheelZoom();
GDownloadUrl("world_xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var first_name = markers[i].getAttribute("first_name");
var last_name = markers[i].getAttribute("last_name");
var email = markers[i].getAttribute("email");
var affiliation = markers[i].getAttribute("affiliation");
var status = markers[i].getAttribute("status");
var service = markers[i].getAttribute("service");
var rank = markers[i].getAttribute("rank");
var specialty = markers[i].getAttribute("specialty");
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var country = markers[i].getAttribute("country");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country) {
var marker = new GMarker(point);
var html = "" + rank + " " + first_name + " " + last_name + " " + service + ", " + status + " " + specialty + " " + affiliation + " " + city + ", " + state + " " + country + " " + email + " " + " ";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
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 )