I'm very new to coding and am creating an online system. Part of the system I have included Google Distance Matrix API which is JavaScript, whereas most of my other code is HTML or PHP. Unfortunately, I need the distance (which is calculated in JavaScript) to be in my PHP code so I can play about with it. I read I could use AJAX? I'm not terribly sure about what I'm doing but I had a go.
Before the page that includes the Google Map, there is a form. This means I have to use SESSION variables to move the data from the page before the Google page, to two pages after the Google page.. this is also where my Google script gets it's two locations to find the distance between. Which all works fine, I think.
PHP on Google page:
$date = $_POST['date'];
$time = $_POST['time'];
$length = $_POST['length'];
$numberofpeople = $_POST['numberofpeople'];
$useofbus = $_POST['useofbus'];
session_start();
$_SESSION['time'] = $time;
$_SESSION['date'] = $date;
$_SESSION['length'] = $length;
$_SESSION['numberofpeople'] = $numberofpeople;
$_SESSION['pickuplocation'] = $pickuplocation;
$_SESSION['destination'] = $destination;
$_SESSION['useofbus'] = $useofbus;
$pickuplocation = $_POST['pickuplocation'];
$destination = $_POST['destination'];
HTML on Google page:
</head>
<body onload="initialize()">
<div id="inputs">
<pre class="prettyprint">
</pre>
<form name="google" action="thirdform.php">
<table summary="google">
<tr>
<td> </td>
<td><input name="Continue" value="Continue" type="submit" ></td>
<td> </td>
</tr>
</table>
</form>
</div>
<div id="outputDiv"></div>
<div id="map"></div>
</body>
</html>
I won't post the JavaScript of the Google Matrix other than the AJAX:
var distance = results[j].distance.text;
$.get("thirdform.php", {miles:distance} );
I'm not sure if the code above is correct, I'm guessing I'm going wrong somewhere, probably here.
On the next page, (thirdform.php) PHP:
session_start();
$time = $_SESSION['time'];
$date = $_SESSION['date'];
$length = $_SESSION['length'];
$numberofpeople = $_SESSION['numberofpeople'];
$pickuplocation = $_SESSION['pickuplocation'];
$destination = $_SESSION['destination'];
$useofbus = $_SESSION['useofbus'];
var_dump($_SESSION);
echo "</br>";
$distance = $_GET['miles'];
echo "DISTANCE: " . $distance . "</br>";
I'm not able to get anything in the PHP variable $distance - it's empty. Am I coding incorrectly? I followed an example on-line from this website somewhere which claimed to work. I've read several articles and searched on Google and on this website but there doesn't seem to be a clear answer anywhere that isn't too complicated and relates to what I'm trying to do. I've read plenty of examples but they're all far too complicated for me to use and change to put into my code. There was some code I read where the page was sent straight to next page however I need to show the Google Map on my page and therefore need to use the button to move to the next page.
Could anyone give me a nudge in the right direction? Thanks.
JS:
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin = '<?php echo $pickuplocation; ?>';
var destination = '<?php echo $destination; ?>';
var destinationIcon = 'https://chart.googleapis.com/chart? chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances()
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
<script type="text/javascript">
var distance = results[j].distance.text;
$('.button-class').click(function() { $.get("thirdform.php", {miles:distance}, function (data){alert(data)} ); });
</script>
Since you are overriding the form action with the $.get, try removing the form and using a <button> instead of an <input> button.
Then have your ajax request run on that <button>.
Edit:
It's also worth noting that you should probably just send data from the php file. You can then do any other manipulation("DISTANCE: ", "<br />") in the html/js.
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’m working on the example: “Using PHP/MySQL with Google Maps”
https://developers.google.com/maps/articles/phpsqlajax_v3
I know this tutorial has been covered a lot before but I can’t find the answer I’m looking for, and hope someone can help.
I’m trying to show a Google Map with markers. Each marker is a book icon. Books are organised by category (I’ve called it “type” in my database). The idea is that users can select which category of book they want, and then only these books will be shown on the map.
My problem is I can’t get the FORM select to work, the “type” variable needs to be passed from the index.php to the page phpsqlajax_genxml2.php, in order for the database to be interrogated.
My question is - how do i get the php variable $type to the phpsqlajax_genxml2.php page?
The phpsqlajax_genxml2.php page is not included in the index.php page, but there is a downloadUrl function:
downloadUrl("phpsqlajax_genxml2.php", function(data)
Here are my files in full. Thanks in advance
index.php
<?php
// Get parameters from URL
$type = $_GET["type"];
?>
<!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 = {
'Murder Mystery': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png'
},
'Travel Guide': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_gray.png'
},
'Romance': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_purple.png'
},
'Short Story': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
},
'Thriller': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
},
'Comedy': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
},
'Graphic Novel': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_white.png'
},
'Satire': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_brown.png'
}
};
</script>
<script type="text/javascript">
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
alert('Geolocation is required for this page, but your browser doesn't support it. Try it with a browser that does, such as Opera 10.60.');
}
function errorFunction(position) {
alert('Error!');
}
//If successful geolocation then draw the map, show my coords on the map, and pull in the icons
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var map = new google.maps.Map(document.getElementById("map"),
{
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// SQL to XML file
//downloadUrl("phpsqlajax_genxml2.php?type=" + type, function(data) {
downloadUrl("phpsqlajax_genxml2.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 + "<br/>" + "<i>" + type + "</i>";
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="successFunction(position)">
<div id="map" style="width: 500px; height: 400px"></div>
<form action="<?php $_PHP_SELF ?>" method="GET">
<select name="type">
<option value="Murder Mystery">Murder Mystery</option>
<option value="Travel Guide">Travel Guide</option>
<option value="Romance">Romance</option>
<option value="Short Story">Short Story</option>
<option value="Thriller">Thriller</option>
<option value="Comedy">Comedy</option>
<option value="Graphic Novel">Graphic Novel</option>
<option value="Satire">Satire</option>
</select>
<input type="submit" value="Submit" />
</form>
</body>
</html>
phpsqlajax_genxml2.php
<?php
// Get parameters from URL
$type = $_GET["type"];
include ("inc/DB_connect.php");
//Using PHP's echo to Output XML
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected)
{
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
//$query = "SELECT * FROM `markers` WHERE 1";
$query = "SELECT * FROM `markers` WHERE `type` = '$type'";
$result = mysql_query($query) or die(mysql_error());
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result))
{
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
So if you want to pass data from one PHP file to another, You have two options in this case, Cookies and Sessions:
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
EDIT
There is one more method supported where you can pass that variable in your JQuery call like this:
In your first file:
jQuery('#map').load('Firstfile.php?type=<?php echo($type);?>');
In your second file
$type = $_GET['type'];
Give this one a shot!!
Referred from Passing php variable from one file to another?
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 am trying to make an array of latitudes and longitudes using cities that I have in a mySQL database. This is what I have so far. I am trying to set up the array variable in javascript, and echo out the fields inside. The "markers" array is read to make markers appear on the google map at the desired locations:
EDIT: Here is the entire script
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// 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: 'Your Current City'
});
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);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
You have a typo: sometimes you use long, at other times lng.
in the code segment:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});}
while earlier you use
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$long.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
In effect, your echo statement, which should be producing longitudes in your array, is referencing a non-initialized variable, $long. Fix that and you should be good to go. In other words, change
$lng = $location->lng;
to
$long = $location->lng;
(or change your echo statement...)
My earlier answer dealt with the typo. I think there's a fundamental issue with "how to draw maps with the google API". The following code snippet (from google JavaScript API shows an example of using overlays (which is what a marker is):
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, }
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!" });
// To add the marker to the map, call setMap();
marker.setMap(map);
Several of these steps appear to be missing from your code - maybe you didn't show them, or maybe you didn't realize you needed them?
EDIT: even after you posted your full code, I still don't see certain things I would expect.
Here are one thing you can try for sure: call the google API before referencing it: add this line
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>
right below <head>, before your <script>
Fixing just this, and taking out a bunch of "superfluous" (for the purpose of "getting a map with a pin") lines, allowed me to create a simple file that can render a map of New York, NY with one marker on it. The source code can be found at http://www.floris.us/SO/maptest.php.txt . From there, you can add more stuff back in...
Further edit: with the lessons learnt, I made http://www.floris.us/SO/maptestFull.php which has most of the functionality you were looking for (not the DB lookup, which I don't have, obviously). Once again, source code is copied in .php.txt file so you can look at it. Slightly messy (from trying to turn things on/off) - you will have to look closely to see all the changes I made.
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.