Monday, May 17, 2010

Google MAP API | Map search within Radius

Post sebelum ni aku ada postkan mysql statement utk query MySQL utk mendapatkan lat &long didalam radius yg kita perlukan.

post ini pula aku sertakan keratan javascript function utk draw radius layer on top of google map.

here's the code:

html:

Find Within Radius The circle drawn here is a circle on the surface of the Earth.

Radius: Miles Kilometers

Javascript:

function drawCircle() {
 var oUnitsMI = document.searchMap.unitsMI;
 var oUnitsKM = document.searchMap.unitsKM;
 var oRadius = document.searchMap.radiusInput;
 oRadius.value = oRadius.value ? oRadius.value : 500;
 
 
 //alert(oRadius.value);
 //circleRadius = oRadius.value;
 if (oRadius.value == '') {
  alert("Enter a number for radius");
  return;
 }
 circleRadius = parseFloat(oRadius.value);
 
 if (circleRadius > 9999) {
  alert("To Large");
  return;
 }
 
 
 if (oUnitsKM.checked) {
  circleUnits = 'KM';
 }
 else {
  circleUnits = 'MI';
 }
 
 doDrawCircle();
 
 //optional features, calling ajax if select in radius checked. uncheck to suite your ajax function
 //if(document.searchMap.inradius.checked){
  // var center = map.getCenter();
 //  var urls = '?action=search¢er=' + center + "&radius=" + circleRadius + "&unit=" + circleUnits;
 //  ajaxpage(urls,'searchcontainer'); 
 //}
}
 
 
function doDrawCircle(){
 
 if (circle) {
  map.removeOverlay(circle);
 }
 
 
 if (centerMarker) {
  map.setCenter(centerMarker.getLatLng())
 }
 else {
  centerMarker = new GMarker(map.getCenter(),{draggable:true});
  GEvent.addListener(centerMarker,'dragend',drawCircle)
  map.addOverlay(centerMarker);
 }
 
 var center = map.getCenter();
 
 var bounds = new GLatLngBounds();
 
 
 var circlePoints = Array();
 
 with (Math) {
  if (circleUnits == 'KM') {
   var d = circleRadius/6378.8; // radians
  }
  else { //miles
   var d = circleRadius/3963.189; // radians
  }
 
  var lat1 = (PI/180)* center.lat(); // radians
  var lng1 = (PI/180)* center.lng(); // radians
 
  for (var a = 0 ; a < 361 ; a++ ) {
   var tc = (PI/180)*a;
   var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
   var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
   var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
   var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
   circlePoints.push(point);
   bounds.extend(point);
  }
 
  if (d < 1.5678565720686044) {
   circle = new GPolygon(circlePoints, '#00BE00', 1, 1, '#3EFF3E', 0.25); 
  }
  else {
   circle = new GPolygon(circlePoints, '#00BE00', 1, 1); 
  }
  map.addOverlay(circle); 
 
  map.setZoom(map.getBoundsZoomLevel(bounds));
  
  
 }
}

kalau diperhatikan di penghujung function drawCircle ada line yg aku comment kan. line berkaitan adalah tambahan utk memanggil function ajax utk retrive data dr mysql ber dasarkan radius circle yg kita draw di atas map.

happy coding.

No comments: