I'm passing 2 arrays into google maps, one for a location (which is geocoded) and another for that location's info window.
Is there any way I can initialize the map and plot all these points at once, or will I have to make a second function to plot more points? Since there are multiple points, I'm not sure how else to do it other than plotting one point, and then making an addition function which loops through the array and plots the rest.
Here's the code.
The two arrays(which I didn't include the code for) are $cityArray and $title
function initialize() {
geocoder = new google.maps.Geocoder();
latlang = geocoder.geocode( { 'address':
'<?php echo json_encode($cityArray); ?>'},
function(results, status) {
//use latlang to enter city instead of coordinates
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click',
(function(marker, i) {
return function() {
infowindow.setContent(
'<?php echo json_encode($title); ?>'
);
infowindow.open(map, marker);
}
})(marker, i));
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: "
+ status);
}
});
var myOptions = {
center: latlang, zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
var gm = google.maps;
map = new google.maps.Map(document.getElementById("main_Content"),
myOptions);
plotMarkers();
} //end of initialization function
var infowindow = new google.maps.InfoWindow();
Please refer the following Sample which i have used for the above.,
Step1 : Include the Three script Files in header of your page.,like
(i). <scrip type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<scrip type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<scrip type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
Step2 : Scripts On Page
<script type="text/javascript">
//initialize the map window
jQuery(document).ready(function () {
load();
});
jQuery(window).unload(function () {
GUnload();
});
var map;
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
//map.setCenter(new GLatLng(35.048629,-0.820663), 4);
searchLocations();
document.getElementById('directions-panel').innerHTML = '';
var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
var print_icon_url_new = 'PrintLink';
jQuery('#print_icon').html(print_icon_url_new);
}
}
//Search Locations with address input
function searchLocations() {
var address = document.getElementById('addressInput').value;
// alert(address);
var address_new = jQuery("#addressInput_new").val();
if (address_new != "Enter City or Zip") {
jQuery("#loc1").html(address_new);
}
geocoder.getLatLng(address, function (latlng) {
//alert(latlng);
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
// Search Near By Location to place the Markers and Information windows
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';
jQuery.get(searchUrl, function (data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
var sidebar_val = '';
//sidebar.innerHTML = 'Results Found';
jQuery("#sidebar").html(sidebar_val);
<!--jQuery("#loc_count").html(markers.length);-->
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(35.048629, -0.820663), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var phone_new = markers[i].getAttribute('phonenumber');
var distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
var markerchar = "b";
var marker = createMarker(point, name, address, phone_new);
map.addOverlay(marker);
// var location_count = jQuery('#loc_count').val();
jQuery('#loc_count').val(i + 1);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);
jQuery('#sidebar').append(sidebarEntry);
//sidebar.appendChild(sidebarEntry);
// ScrollPane.getContentPane().appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
jQuery('#sidebar').jScrollPane();
//jQuery('#sidebar').reinitialise();
});
}
//To Create a Marker With Information Window
function createMarker(point, name, address, phone_new) {
var pinkIcon = new GIcon(G_DEFAULT_ICON);
pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
var markerOptions = {
icon: pinkIcon
};
var marker = new GMarker(point, markerOptions);
var event_calendar = "event_calendar";
var event_title = ""+ benObj.event_title +"";
var display = "block";
var e_dt_start = jQuery("#dtstart").val();
var e_dt_end = jQuery("#dtend").val();
var e_start_timestamp = (formatTimestring(e_dt_start));
var e_end_timestamp = (formatTimestring(e_dt_end));
var e_desc = jQuery("#edesc").val();
var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br>Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div> | Remind Me<br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;"> <input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
GEvent.addListener(marker, 'click', function () {
marker.openInfoWindowHtml(html);
//jQuery(this).addtocal();
});
return marker;
}
// To Make Sidebar Entry If need
function createSidebarEntry(marker, name, address, distance, phone_new) {
var div = document.createElement('div');
var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' – '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am – 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function () {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function () {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function () {
div.style.backgroundColor = '#fff';
});
return div;
}
// To make a Directions If need
function calcRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
var print_icon_url = 'PrintLink';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
directionsDisplay.setDirections(response);
jQuery('#print_icon').html(print_icon_url);
}
});
}
</script>
//To Create a XML For Markers and Information Windows
<?php
function mapMarker($center_lat,$center_lng,$radius)
{
$mysqli = $this->_getMySqlConnection();
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Search the rows in the markers table
$query = sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($center_lng),
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($radius));
$result = $mysqli->query($query);
header("Content-type: text/xml");
header('Access-Control-Allow-Origin: *');
$avoid_duplicate="";
// Iterate through the rows, adding XML nodes for each
while ($row = #$result->fetch_assoc())
{
if($avoid_duplicate!=$row['store_name'])
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['store_name']);
$newnode->setAttribute("address", $row['street_address_1']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("phonenumber", $row['phone']);
$avoid_duplicate=$row['store_name'];
}
}
$outXML=$dom->saveXML();
$result->close();
$mysqli->close();
return $outXML;
}
?>
HTML Part :
<div class="mapleft">
<div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
<div class="mapshadow"></div>
</div>
<input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect" value="50" />
<input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect_temp" value="50" />
<input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />
These are the things which will produce the great out comes.
Related
i have a problem with showing my XML File in my Google Maps
My Concept : MySQL -> XML -> Show To GMaps
Here's My Code :
Index.php
<!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>ODP Tracking</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
var customIcons = {
FTTH: {
icon:"/images/ico_tag.png"
},
MSAN: {
icon:"/images/ico_tag_ms.png"
},
DSLAM: {
icon:"/images/ico_tag_ds.png"
},
bar: {
icon:'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(load);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function updateMarkerPosition(latLng) {
document.getElementById('latitude').value = [latLng.lat()]
document.getElementById('longitude').value = [latLng.lng()]
}
function load(position) {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom: 17,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var url = "phpsqlajax_genxml.php";
var marker2 = new google.maps.Marker({
position : latLng,
title : 'Lokasi',
map : map,
draggable : false
});
// Change this depending on the name of your PHP file
downloadUrl(url, 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 kap = markers[i].getAttribute("kap");
var avai = markers[i].getAttribute("avai");
var type = markers[i].getAttribute("type");
var note = markers[i].getAttribute("ket");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lang")));
var html = "<b>" + name + "</b> <br/>ALPRO : " + type + "<br/>KAP : " + kap + "<br/>AVAI : " + avai + "<br/>KETERANGAN : " + ket ;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, marker2, map, infoWindow, html);
}
});
updateMarkerPosition(latLng);
google.maps.event.addListener(marker2, 'drag', function() {
updateMarkerPosition(marker2.getPosition());
});
}
function bindInfoWindow(marker, marker2, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker, marker2);
});
}
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="getLocation()">
<style>
html, body, #map {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map {
position: relative;
}
</style>
<div id="map"></div>
</body>
</html>
and here's my XML Parsing Code
phpsqlajax_genxml.php
<?php
require("phpsqlajax_dbinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
$xmlStr=str_replace("-",'-',$xmlStr);
$xmlStr=str_replace("/",'/',$xmlStr);
return $xmlStr;
}
// Create connection
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
// Select all the rows in the markers table
$sql = "SELECT * FROM koordinat_odp";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . 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 = $result->fetch_assoc()){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['nama_dp']) . '" ';
echo 'kap="' . $row['kap'] . '" ';
echo 'avai="' . $row['avai'] . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lang="' . $row['lang'] . '" ';
echo 'type="' . $row['jenis_alpro'] . '" ';
echo 'ket="' . $row['note'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
My Problem : It not showing marker on the maps, i generate xml file myself in browser, it work, but not showing in gmaps
Thank you in advance for all you helps .
I think your answer can be found here.
function parseXML(xml){
var bounds = new google.maps.LatLngBounds();
$(xml).find("marker").each(function(){
//Read the name, address, latitude and longitude for each Marker
var name = $(this).find('name').text();
var kap = $(this).find('kap').text();
var avai = $(this).find('avai').text();
var note = $(this).find('ket').text();
var type = $(this).find('type').text();
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var markerCoords = new google.maps.LatLng(parseFloat(lat),
parseFloat(lng));
bounds.extend(markerCoords);
var marker = new google.maps.Marker({position: markerCoords, map:map});
});
map.fitBounds(bounds);
}
I'm developing a mobile app that allows a user to record some data about their favourite monuments. Now, when a user takes a photo of their monument the lat and long values are instantly recorded. Giving me two separate values.
The user then syncs this data with my PostGreSQL database. I want to manipulate this data on my website service.
All I want is a simple map plugin which will take each (so like a foreach loop) record relating to a user (name of monument, lat and long) and display it on a map with icon markers.
So for example, you could have a favourite monument in Cardiff and one in London. You would have two markers displayed on your account map and when you click on their a pop-up says 'Cardiff Museum' and 'London Eye'.
I've tried multiple searches on Google but to no avail.
Has anyone ever implemented something similar? I'm good with either PHP or JQuery or both solutions!
Here is the code where you can pass multiple lat-long combinations to add a marker for each user location.
Repeat this code for every marker you need in your loop to traverse locations array.
t.push('Location Name 1');
x.push(33.84659); // you can write like x.push(<?php echo $userloc[0]['lat']?>)
y.push(-84.35686);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
The complete code is given below.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() { initialize(); });
function initialize() {
var map_options = {
center: new google.maps.LatLng(33.84659,-84.35686),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
var info_window = new google.maps.InfoWindow({
content: 'loading'
});
var t = [];
var x = [];
var y = [];
var h = [];
t.push('Location Name 1');
x.push(33.84659);
y.push(-84.35686);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
t.push('Location Name 2');
x.push(33.846253);
y.push(-84.362125);
h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');
var i = 0;
for ( item in t ) {
var m = new google.maps.Marker({
map: google_map,
animation: google.maps.Animation.DROP,
title: t[i],
position: new google.maps.LatLng(x[i],y[i]),
html: h[i]
});
google.maps.event.addListener(m, 'click', function() {
info_window.setContent(this.html);
info_window.open(google_map, this);
});
i++;
}
}
</script>
<div id="map_canvas" style="width:400px;height:400px;">Google Map</div>
This code may help you. You can see its working demo here(http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=-33.866603&lon=151.207108&setLatLon=Set)
<!-- Original script taken from: http://conversationswithmyself.com/googleMapDemo.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<style type="text/css">
<!--
h1 {
font-family:sans-serif;
color:blue;
text-align: center;
font-size:120%;
}
.tekst {
font-family:sans-serif;
color:blue;
font-size:100%;
}
.smalltekst {
font-family:sans-serif;
color:black;
font-size:80%;
}
-->
</style>
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAF4PVqw0p5l92pEmE39k0MRQWxhPw7-SAnMb84NfHs4vQ3HTp4BTb-yeL6fQg7Up9d9idBGy5naXydw" type="text/javascript"></script>
<title>Google Maps Latitude, Longitude Popup</title>
</head>
<body>
<h1>Google Maps Latitude, Longitude Popup</h1>
<div style="width: 600px;" class="tekst"><b>Simply click on the map on a location and it will provide you with the latitude and longitude in the callout window.</b></div>
<div id="map" style="width: 600px; height: 400px"></div>
<div id="geo" style="width: 300px;position: absolute;left: 620px;top: 100px;" class="tekst">
<form name="setLatLon" action="googleMapLocation.php">
<b>* Coordinates:</b><br />
<table>
<tr><td>* Lat:</td><td><input type='text' name='lat' id="frmLat"></td></tr>
<tr><td>* Lon:</td><td><input type='text' name='lon' id="frmLon"></td></tr>
</table>
<input type="submit" name="setLatLon" value="Set"><br />
</form><br />
<b>* Flickr tags:</b><br />
<textarea id="geocode" cols="30" rows="2"></textarea><br />
<br />
<b>* RoboGEO tags:</b><br />
<textarea id="geocodeRoboGEO" cols="30" rows="2"></textarea><br />
* Show location on Multimap<br />
* Permanent Link<br /><br />
<script type="text/javascript">
<!--
google_ad_client = "pub-1588116269263536";
google_alternate_color = "FFFFFF";
google_ad_width = 234;
google_ad_height = 60;
google_ad_format = "234x60_as";
google_ad_type = "text";
//2006-09-30: Map
google_ad_channel ="0993881556";
google_color_border = "DDDDDD";
google_color_bg = "DDDDDD";
google_color_link = "0000FF";
google_color_text = "333333";
google_color_url = "333333";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<div style="width: 600px;" class="smalltekst">
<p><i>Address lookup has been removed because it violated the ToS of Google Maps.</i></p>
Based on code taken from this website and this website.<br />
All other errors are caused by code written by Pierre Gorissen.<br />
</div>
<script type="text/javascript">
//<![CDATA[
var baseLink = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php";
var multimapBaseLink = "http://www.multimap.com/map/browse.cgi?scale=10000&icon=x";
var geocoder = new GClientGeocoder();
var setLat = 51.618017;
var setLon = 2.48291;
// argItems code taken from
// http://www.evolt.org/article/Javascript_to_Parse_URLs_in_the_Browser/17/14435/?format=print
function argItems (theArgName) {
sArgs = location.search.slice(1).split('&');
r = '';
for (var i = 0; i < sArgs.length; i++) {
if (sArgs[i].slice(0,sArgs[i].indexOf('=')) == theArgName) {
r = sArgs[i].slice(sArgs[i].indexOf('=')+1);
break;
}
}
return (r.length > 0 ? unescape(r).split(',') : '')
}
function getCoordForAddress(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address\n\n Sorry, dat adres bestaat blijkbaar niet!");
} else {
place = response.Placemark[0];
setLat = place.Point.coordinates[1];
setLon = place.Point.coordinates[0];
setLat = setLat.toFixed(6);
setLon = setLon.toFixed(6);
document.getElementById("frmLat").value = setLat;
document.getElementById("frmLon").value = setLon;
}
placeMarker(setLat, setLon)
}
function placeMarker(setLat, setLon) {
var message = "geotagged geo:lat=" + setLat + " geo:lon=" + setLon + " ";
document.getElementById("geocode").value = message;
var messageRoboGEO = setLat + ";" + setLon + "";
document.getElementById("geocodeRoboGEO").value = messageRoboGEO;
document.getElementById("geocode").focus();
document.getElementById("geocode").select();
document.getElementById("maplink").href = baseLink + "?lat=" + setLat + "&lon=" + setLon ;
document.getElementById("multimap").href = multimapBaseLink + "&lat=" + setLat + "&lon=" + setLon ;
document.getElementById("frmLat").value = setLat;
document.getElementById("frmLon").value = setLon;
var map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl()); // added
map.addControl(new GMapTypeControl()); // added
map.centerAndZoom(new GPoint(setLon, setLat), 12);
var point = new GPoint(setLon, setLat);
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(map, 'click', function(overlay, point) {
if (overlay) {
map.removeOverlay(overlay);
} else if (point) {
map.recenterOrPanToLatLng(point);
var marker = new GMarker(point);
map.addOverlay(marker);
var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( point );
if ( matchll ) {
var lat = parseFloat( matchll[1] );
var lon = parseFloat( matchll[2] );
lat = lat.toFixed(6);
lon = lon.toFixed(6);
var message = "geotagged geo:lat=" + lat + " geo:lon=" + lon + " ";
var messageRoboGEO = lat + ";" + lon + "";
} else {
var message = "<b>Error extracting info from</b>:" + point + "";
var messagRoboGEO = message;
}
marker.openInfoWindowHtml(message);
document.getElementById("geocode").value = message;
document.getElementById("geocodeRoboGEO").value = messageRoboGEO;
document.getElementById("geocode").focus();
document.getElementById("geocode").select();
document.getElementById("maplink").href = baseLink + "?lat=" + lat + "&lon=" + lon ;
document.getElementById("multimap").href = multimapBaseLink + "&lat=" + lat + "&lon=" + lon ;
document.getElementById("frmLat").value = lat;
document.getElementById("frmLon").value = lon;
}
});
}
function findAddress() {
myAddress = document.getElementById("address").value;
geocoder.getLocations(myAddress, getCoordForAddress);
}
if (argItems("lat") == '' || argItems("lon") == '') {
placeMarker(setLat, setLon);
} else {
var setLat = parseFloat( argItems("lat") );
var setLon = parseFloat( argItems("lon") );
setLat = setLat.toFixed(6);
setLon = setLon.toFixed(6);
placeMarker(setLat, setLon);
}
//]]>
</script>
<!-- Start twatch code -->
<script type="text/javascript"><!--
//<![CDATA[
document.write('<scr'+'ipt type="text/javascript" src="/Pierre/twatch/jslogger.php?ref='+( document["referrer"]==null?'':escape(document.referrer))+'&pg='+escape(window.location)+'&cparams=true"></scr'+'ipt>');
//]]>
//--></script>
<!-- End twatch code -->
</body>
</html>
I am trying to place markers where the cities in a mySQL database are. The page loads but it shows "map div" where the map should load. I am not sure what is wrong. Thank you for taking a look and trying to help!
<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);
//create an array of latitudes, longitudes, and city names
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>
I need a way to find the postcode of a UK location if I know its latitude and longitude.
For example:
address:Old Deer Park, Richmond, Greater London TW9 2SL, United Kingdom
Latitude = 51.4691, Longitude = -0.2963
Using this information I need a way to programmatically retrieve that location's postcode.
The problem you're trying to solve is called reverse geocoding. Just look at the Google maps documentation, which gives examples. It boils down to a URL with a latlng paramater, you have a choice of XML or JSON. There can be many results, so you'll have to loop over the returned structure and pick the most appropriate.
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.4691,-0.2963&sensor=false
Example usage using CURL + JSON.
function getPostcode($lat, $lng) {
$returnValue = NULL;
$ch = curl_init();
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=false";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
$json = json_decode($result, TRUE);
if (isset($json['results'])) {
foreach ($json['results'] as $result) {
foreach ($result['address_components'] as $address_component) {
$types = $address_component['types'];
if (in_array('postal_code', $types) && sizeof($types) == 1) {
$returnValue = $address_component['short_name'];
}
}
}
}
return $returnValue;
}
echo getPostcode(51.4691, -0.2963);
It isn't a part of Google maps - but there's a UK postcode API here:
http://www.uk-postcodes.com/api.php
It allows you to send it a request including lat and lon of a position and it will return the UK postcode for that location.
No idea if it works, but worth a try!
i have already use this code: how to get postcode special uk USing this code ..
and the estimated journey time for from_address to to_address .
<style>
.ui-autocomplete {background-color: white;width: 300px;border: 1px solid #cfcfcf;list-style-type: none;padding-left: 0px}
#intro-text{margin:20px 0}
#map_canvas {width: 720px;height: 200px;margin-top:20px;clear:both;display:none}
#from_box {margin-left:0px}
#to_box, #from_box {float:left;margin-left:10px}
#img_arrow {float:left;margin:30px 50px 0 50px}
#results{margin: 20px 0 10px 0; overflow:hidden}
#distance_direct{float:left;width:40%;border:1px solid black;margin-left:60px;height:90px}
#distance_road{float:left;width:40%;border-right:1px solid black; border-top:1px solid black; border-bottom:1px solid black;height:90px}
.ui-menu-item a {color:black;font-weight:bold;cursor:pointer}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var geocoder = new google.maps.Geocoder();
// This function formats numbers by adding commas
function numberFormat(nStr,prefix){
var prefix = prefix || '';
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
return prefix + x1 + x2;
}
$("#from_address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
//latitude: item.geometry.location.lat(),
//longitude: item.geometry.location.lng()
}
}));
})
}
});
$("#to_address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
//latitude: item.geometry.location.lat(),
//longitude: item.geometry.location.lng()
}
}));
})
}
});
$('#get_results').click(function() {
if($('#from_address').val() == "" || $('#from_address').val() == "") {
$('#results').hide();
$('#map_canvas').hide();
$('#error_msg').show().html('Please make sure you have entered both a "From" and "To" address.');
return;
} else {
$('#error_msg').hide();
}
var location1;
var location2;
var formatted_from_address;
var formatted_to_address
$('#crow_dist').empty();
$('#drive_dist').empty();
geocoder.geocode( { 'address': $('#from_address').val() }, function(results, status ) {
if (status == google.maps.GeocoderStatus.OK) {
//location of first address (latitude + longitude)
location1 = results[0].geometry.location;
formatted_from_address = results[0].formatted_address;
$('#from_address').val( formatted_from_address );
//////////////////////////////////////////////
geocoder.geocode( { 'address': $('#to_address').val() }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//location of first address (latitude + longitude)
location2 = results[0].geometry.location;
formatted_to_address = results[0].formatted_address;
$('#to_address').val(formatted_to_address);
var latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);
var myOptions = {
zoom:10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Make sure maps shows both markers
var southWest = new google.maps.LatLng(location1.lat(),location1.lng());
var northEast = new google.maps.LatLng(location2.lat(),location2.lng());
var bounds = new google.maps.LatLngBounds(southWest,northEast);
document.getElementById("lat1").value = southWest;
document.getElementById("lat2").value = northEast;
map.fitBounds(bounds);
// show route between the points
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
suppressInfoWindows: false
});
directionsDisplay.setMap(map);
var request = {
origin:location1,
destination:location2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distance = numberFormat( Math.round( (response.routes[0].legs[0].distance.value) * 0.000621371192 ) );
$("#drive_dist").html('<div style="font-weight:bold;font-size:1.6em;margin-bottom:5px">' + distance + ' mi.</div><div style="font-style:italic">Get Directions</div>');
} else {
$("#drive_dist").html('<div style="font-weight:bold;font-size:1.6em;margin-bottom:5px">Not Available</div>');
}
document.getElementById("distance1").value = distance;
});
$('#directionsPanel').empty();
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker1 = new google.maps.Marker({
map: map,
position: location1,
title: "From: " + $('#from_address').val()
});
var marker2 = new google.maps.Marker({
map: map,
position: location2,
title: "To: " + $('#to_address').val()
});
//DD=$('#from_address').val();
// create the text to be shown in the infowindows
var text1 = '<div style="width:100px"><b>From:</b> '+formatted_from_address+'</div>';
var text2 = '<div style="width:100px"><b>To:</b>'+formatted_to_address+'</div>';
// create info boxes for the two markers
var infowindow1 = new google.maps.InfoWindow({
content: text1
});
var infowindow2 = new google.maps.InfoWindow({
content: text2
});
// add action events so the info windows will be shown when the marker is clicked
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map,marker2);
});
function toRad(deg) {
return deg * Math.PI/180;
}
// compute distance between the two points
var R = 6371; // Radius of the earth in km
var dLat = toRad(location2.lat()-location1.lat());
var dLon = toRad(location2.lng()-location1.lng());
var dLat1 = toRad(location1.lat());
var dLat2 = toRad(location2.lat());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(dLat1) * Math.cos(dLat1) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = (R * c) * 0.621371192; // Distance in miles;
$("#crow_dist").html('<div style="font-weight:bold;font-size:1.6em;margin-bottom:5px">' + numberFormat( Math.round(d) ) + ' mi.</div><div style="font-style:italic">"As the Crow Flies"</div>');
$('#map_canvas').show();
} else {
alert("Geocode for Address 2 was not successful for the following reason: " + status);
}
});
} else {
alert("Geocode for Address 1 was not successful for the following reason: " + status);
}
});
$('#results').show();
});
if($('#from_address').val() != '' || $('#to_address').val() != '') {
$('#get_results').trigger('click');
}
});
</script>
<div id="map_canvas"></div>
I am fairly new to php and have not figured out how I would perform a certain task.
My code has the user input their address and then choose radius to
search, after they search a map is generated that shows the 3 closest
locations to their address.
I want to make it so that when the user clicks on the marker from the
map it generates a page for that item clicked. saying you clicked on
"store name". Could you please help me understand how this could be
done? Thank you.
<?php
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// 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());
}
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 3",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>
and
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onload="load()">
<div>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="3" selected>3mi</option>
<option value="5">5mi</option>
<option value="10">10mi</option>
<option value="25">25mi</option>
</select>
<input type="button" onclick="searchLocations();" value="Search"/>
</div>
<div><select id="locationSelect" style="width:500;visibility:hidden"></select></div>
<div id="map" style="width: 500; height: 500"></div>
</body>
</html>
In JS exist a global variable location. By changing the href attribute you can force the browser to open another url. docu: http://www.w3schools.com/jsref/obj_location.asp
If you need information about the clicked marker you can put this information in a closure scope, to reuse it later when the marker is clicked. The create-function is called on runtime and the returned anonymous function is called by the click event.
Pseudocode:
function createCLickCallback(marker) {
return function () {
var position = marker.getPosition();
location.href = "locationInfo.php?lat=" + position.lat() + "&lng=" + position.lng();
};
}
google.maps.event.addListener(marker, 'click', createCLickCallback(marker));
in your JS function "createMarker" you are adding listener to marker click event:
google.maps.event.addListener(marker, 'click', function() {
...
});
you should add your "page generation" code (whatever it is either open new page or update some part of current page) inside event callback function. In your current code google infowindow will be opened over your marker.