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>
Related
I am using the following script to show maps in my application. there are some issues coming :
it's displaying only 10 places.
it showing provided a place in wrong place.
when I want to see only one place then background roadmap is not coming.
I want to display on India map but it's not coming.
Please help me out with this issues.
var graphVal = Kavitha, Ahmedabad, Gujarat##Chavand, Amreli, Gujarat##Khadol, Anand, Gujarat##Ramgadhi, Arvalli, Gujarat##Vagharol, Banas kantha, Gujarat##Matar, Bharuch , Gujarat##Patana, Bhavnagar, Gujarat##Dhasa Vishi, Botad , Gujarat##Panchwada, Dahod, Gujarat##Pimpari, Dang, Gujarat##Rajpar, Devbhumi Dwarka , Gujarat##Harmadiya
, Gir Somnath , Gujarat##Jamvanathali;
var mapid = 'map';
var zoomNo = 15;
graphVal = graphVal.replace(/##\s*$/, "");
var graphvalue = graphVal.split('##');
var ccont = graphvalue.length;
var locations = [];
var geocoder = new google.maps.Geocoder();
var address = '';
var addresArr = [];
for (var i = 0; i < ccont; i++) {
var k = 1;
address = graphvalue[i].replace('SDH', 'Sub District Hospital');
address = address.replace('DH', 'District Hospital');
address = address.replace('-', ' ');
// address = graphvalue[i];
addresArr[i+1] = graphvalue[i];
geocoder.geocode( { 'address': address}, function(results, status) {
// console.log(results[0]);
var tempArray = [];
if (status == google.maps.GeocoderStatus.OK)
{
var Latitudee = results[0].geometry.location.lat();
var Longitudee = results[0].geometry.location.lng();
tempArray.push(addresArr[k]);
tempArray.push(Latitudee);
tempArray.push(Longitudee);
tempArray.push(k);
k++;
}
if (typeof tempArray !== 'undefined' && tempArray.length > 0) {
locations.push(tempArray);
}
});
}
setTimeout(
function()
{
fillMap(locations,mapid,zoomNo);
}, 1000);
function fillMap(locations,mapid,zoomNo){
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [
iconURLPrefix + 'red-dot.png',
iconURLPrefix + 'green-dot.png',
iconURLPrefix + 'blue-dot.png',
iconURLPrefix + 'orange-dot.png',
iconURLPrefix + 'purple-dot.png',
iconURLPrefix + 'pink-dot.png',
iconURLPrefix + 'yellow-dot.png'
]
var iconsLength = icons.length;
var map = new google.maps.Map(document.getElementById(mapid), {
zoom: zoomNo,
//scrollwheel: false,
// center: new google.maps.LatLng(28.6139, 77.2090),
// mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
});
var infowindow = new google.maps.InfoWindow({
maxWidth: 160
});
var markers = new Array();
var iconCounter = 0;
// Add the markers and infowindows to the map
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: icons[iconCounter]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
iconCounter++;
// We only have a limited number of possible icon colors, so we may have to restart the counter
if(iconCounter >= iconsLength) {
iconCounter = 0;
}
}
autoCenter(markers,map);
}
function autoCenter(markers,map) {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].position);
}
// Fit these bounds to the map
map.fitBounds(bounds);
}
Thanks & Regards,
Asjad
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'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.
I started with https://developers.google.com/maps/articles/phpsqlajax_v3 and am using
https://developers.google.com/maps/articles/phpsqlsearch_v3 to try to dynamically filter the content from a mysql DB and update my markers based on the returned results.
My php returns a valid xml file so no worries there. I'm just not sure what I'm doing wrong for the clearing and creating the new markers from the new query.
The load() function gives me a nice new map with markers on it, but the form doesn't seem to do anything. I even tried just have the form button call clearLocations() and nothing happens. The screen kinda blinks but all the points stay there.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Property Sales</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var markersArr = [];
var map;
var infoWindow;
function updateMap(){
var maxbid = document.getElementById('maxbid').value;
var minbid = document.getElementById('minbid').value;
var salestatus = document.getElementById('salestatus').value;
var saledate = document.getElementById('saledate').value;
infoWindow = new google.maps.InfoWindow;
var queryString = "phpsqlajax_genxml3dynamic.php?maxbid=" + maxbid + "&minbid=" + minbid + "&salestatus=" + salestatus + "&saledate=" + saledate;
//var queryString = "phpsqlajax_genxml3dynamic.php?maxbid=" + maxbid + "&minbid=" + minbid;
queryString="phpsqlajax_genxml3dynamic.php?maxbid=340000&minbid=0&salestatus=*&saledate=*";
downloadUrl( queryString, function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
clearLocations();
for (var i = 0; i < markers.length; i++) {
var SaleDate = markers[i].getAttribute("SaleDate");
var CaseNumber = markers[i].getAttribute("CaseNumber");
var Address = markers[i].getAttribute("Address");
var ZipCode = markers[i].getAttribute("ZipCode");
var Plaintiff = markers[i].getAttribute("Plaintiff");
var Defendant = markers[i].getAttribute("Defendant");
var Attorney = markers[i].getAttribute("Attorney");
var SoldTo = markers[i].getAttribute("SoldTo");
var PID = markers[i].getAttribute("PID");
var Appraisal = markers[i].getAttribute("Appraisal");
var MinBid = markers[i].getAttribute("MinBid");
var SaleAmt = markers[i].getAttribute("SaleAmt");
var SaleStatus = markers[i].getAttribute("SaleStatus");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitude")),
parseFloat(markers[i].getAttribute("Longitude"))
);
var info = "<b>Sale Date:" + SaleDate +"<br/>Address:"+ Address+"<br/>Sale Amount:" + SaleAmt + "</b> <br/>Sale Date:" + SaleDate+ "<br/>Case Number:"+ CaseNumber+ "<br/>Address:"+ Addre\
ss+ "<br/>Zipcode:"+ ZipCode+ "<br/>Plaintiff:"+ Plaintiff+ "<br/>Defendant:"+ Defendant+ "<br/>Attorney:"+ Attorney+ "<br/>Sold to:"+ SoldTo+ "<br/>Parcel ID:"+ PID+ "<br/>Appraisal:"+ Appraisal+\
"<br/>Minimum bid:"+ MinBid+ "<br/>Sale amount:"+ SaleAmt+ "<br/> Sale status:"+ SaleStatus;
var icon = customIcons[SaleStatus] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, info);
markersArr.push(marker);
}
});
}
var customIcons = {
ACTIVE: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
CANCELLED: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
NOBIDNOSALE: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
SOLD: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markersArr[i].setMap(null);
}
markersArr.length = 0;
}
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39.7620028,-84.3542049),
zoom: 10,
mapTypeId: 'roadmap'
});
infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
// downloadUrl("phpsqlajax_genxml3.php", function(data) {
downloadUrl( "phpsqlajax_genxml3dynamic.php?maxbid=54,000&minbid=0&salestatus=*&saledate=*", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var SaleDate = markers[i].getAttribute("SaleDate");
var CaseNumber = markers[i].getAttribute("CaseNumber");
var Address = markers[i].getAttribute("Address");
var ZipCode = markers[i].getAttribute("ZipCode");
var Plaintiff = markers[i].getAttribute("Plaintiff");
var Defendant = markers[i].getAttribute("Defendant");
var Attorney = markers[i].getAttribute("Attorney");
var SoldTo = markers[i].getAttribute("SoldTo");
var PID = markers[i].getAttribute("PID");
var Appraisal = markers[i].getAttribute("Appraisal");
var MinBid = markers[i].getAttribute("MinBid");
var SaleAmt = markers[i].getAttribute("SaleAmt");
var SaleStatus = markers[i].getAttribute("SaleStatus");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitude")),
parseFloat(markers[i].getAttribute("Longitude")));
var info = "<b>Sale Date:" + SaleDate +"<br/>Address:"+ Address+"<br/>Sale Amount:" + SaleAmt + "</b> <br/>Sale Date:" + SaleDate+ "<br/>Case Number:"+ CaseNumber+ "<br/>Address:"+ Addre\
ss+ "<br/>Zipcode:"+ ZipCode+ "<br/>Plaintiff:"+ Plaintiff+ "<br/>Defendant:"+ Defendant+ "<br/>Attorney:"+ Attorney+ "<br/>Sold to:"+ SoldTo+ "<br/>Parcel ID:"+ PID+ "<br/>Appraisal:"+ Appraisal+\
"<br/>Minimum bid:"+ MinBid+ "<br/>Sale amount:"+ SaleAmt+ "<br/> Sale status:"+ SaleStatus;
var icon = customIcons[SaleStatus] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, info);
markersArr.push(marker);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<form name='myForm'>
Min Bid $ :<input type='text' id='minbid' value='1,000' /> and
$ :<input type='text' id='maxbid' value='1,000,000' /> <br>
Sale Status:<select id='salestatus'>
<option value="*" selected>All</option>
<option>Active</option>
<option>Sold</option>
<option>Cancelled</option>
<option>No Bid, No Sale</option>
</select>
<br>
Sale Date:<select id='saledate'>
<option value="*" selected>All</option>
<option>2012-06-08</option>
<option>2012-06-01</option>
<option>2012-05-25</option>
<option>2012-05-18</option>
<option>2012-05-11</option>
<option>2012-05-04</option>
<option>2012-04-27</option>
<option>2012-04-20</option>
<option>2012-04-13</option>
<option>2012-04-06</option>
<option>2012-03-30</option>
<option>2012-03-23</option>
<option>2012-03-16</option>
<option>2012-03-09</option>
<option>2012-03-02</option>
</select>
<input type='button' onclick='updateMap()' value='Update Map' />
</form>
<div id="map" style="width: 95%; height: 85%"></div>
</body>
</html>
Again I'm 99.9% sure the php is fine since it returns valid results which are used to populate the field. I'm befuddled as to what I've done wrong for the update.
Hey SO this isn't spam let me post this dang question.
Your clearLocations function is looping over markers not markersArr which contains the existing marker references.
Should be
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markersArr.length; i++) {
markersArr[i].setMap(null);
}
markersArr.length = 0;
}
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.