Read 215 times | Created 2013-09-20 02:05:07 | Updated 2013-09-20 04:05:26 | | |

 

//-- namafile: db.config.php
<?php
/*
DROP TABLE IF EXISTS `tbl_commodity`;
CREATE TABLE IF NOT EXISTS `tbl_commodity` (
  `id_commodity` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `commodity_name` VARCHAR(25) COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id_commodity`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

--
-- Dumping data for table `tbl_commodity`
--

INSERT INTO `tbl_commodity` (`commodity_name`) VALUES
('Padi'),('Bawang Merah'),('Ubi jalar'),('Jagung'),('Bawang Daun');

DROP TABLE IF EXISTS `tbl_location`;
CREATE TABLE IF NOT EXISTS `tbl_location` (
  `id_loc` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `location_name` VARCHAR(25) COLLATE utf8_general_ci NOT NULL,
  `lng` float NOT NULL,
  `lat` float NOT NULL,
  PRIMARY KEY (`id_loc`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

--
-- Dumping data for table `tbl_location`
--

INSERT INTO `tbl_location` (`location_name`, `lng`, `lat`) VALUES
('Ciawigebang', 108.58515, -6.97217),
('Cibingbin', 108.76253, -7.05836),
('Cidahu', 108.64332, -6.98103),
('Cigugur', 108.46167, -6.96803),
('Cimahi', 108.70038, -6.98776),
('Ciniru', 108.50231, -7.04346),
('Cipicung', 108.54398, -6.94466),
('Darma', 108.40450, -7.00528),
('Jalaksana', 108.48816, -6.92315),
('Japara', 108.51658, -6.90166),
('Garawangi', 108.54109, -6.99864),
('Hantara', 108.45705, -7.05693),
('Kadugede', 108.45485, -7.00175),
('Kalimanggis', 108.61445, -6.96854),
('Karamatmulya', 108.49100, -6.92978),
('Kuningan', 108.47684, -6.98144),
('Lebakwangi', 108.60400, -7.01700),
('Luragung', 108.63904, -7.01741),
('Mandirancan',108.47124, -6.81047),
('Nusaherang', 108.44607, -7.00844),
('Pancalang',108.49457, -6.82097),
('Paswahan', 108.42865, -6.80426),
('Sindangagung',108.53522, -6.97492);


DROP TABLE IF EXISTS `rel_loc_commodity`;
CREATE TABLE IF NOT EXISTS `rel_loc_commodity` (
  `id_loc` int(11) UNSIGNED NOT NULL,
  `id_commodity` TINYINT UNSIGNED NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

--
-- Dumping data for table `rel_loc_commodity`
--

INSERT INTO `rel_loc_commodity` (`id_loc`, `id_commodity`) VALUES
(1,1),(2,1),(2,4),(3,2),(4,4),(4,5),(5,4),(6,2),(7,3),(7,4),(8,4),(8,5),
(9,2),(9,5),(10,3),(11,2),(12,2),(13,5),(14,2),(15,2),(15,3),(15,5),(16,2),
(17,1),(18,1),(19,1),(19,3),(20,3),(21,1),(21,3),(22,4),(23,3);
*/
  $dbhost='localhost';
  $dbuser='root';
  $dbpass='';
  $dbname='test';
  $db=new mysqli($dbhost,$dbuser,$dbpass,$dbname);
?>

//-- namafile: maps.php
<!DOCTYPE hmtl>
<html>
  <head>
    <title>Commodities Maps</title>
    <style>
      .detailmap {width:400px;min-width:50px; float:left;margin:5px;}
      .smallmap {width:400px;float:left;height:300px;margin:5px;}
      </style>
  </head>
  <body onload='init()'>
<script>
</script>
<section id="Peta">  
  <b>Location </b> 
  <input id="address" type="textbox" value="Kuningan" onBlur="codeAddress()">
  <input type="text" id = "lat"  size="20" tabindex="3" placeholder="Latitude &deg;North" value="-6.929"/> 
  <input type="text" id = "lng"  size="20" tabindex="4" placeholder="Longitude &deg;East" value="108.461"/>
  <p><b>Select Commodity</b> :
    <select onchange="show_location(this.value)" id="commodity">
      <option value="">-- Select --</option>
      <?php 
      include "db.config.php";
      $sql = "SELECT * FROM tbl_commodity";
      if($result = $db->query($sql)){
        while($record = $result->fetch_object())
        {
          echo '<option value="'.$record->id_commodity.'">' .$record->commodity_name.'</option>';
        }
        $result->close();
      }
      ?>
    </select>
  </p>
  <div id="map" class="smallmap"></div>
  <div id="loc_detail" class="detailmap"></div>
  <br />
</section>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="openlayer/OpenLayers.js"></script>
<script> 
  var map, layer ,geolayer,geocoder,lat,lng,latlong;
  function init(){
      geocoder = new google.maps.Geocoder();
      map = new OpenLayers.Map('map', {maxResolution:'auto'});
      layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
          "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'} );
      map.addLayer(layer);
      getLocation();  
  }
  function getLocation()
  {
    if (navigator.geolocation)
    {
      navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else
    {
      alert("Geolocation is not supported by this browser.");
    }
  }
  function showPosition(position)
  {
    lat=position.coords.latitude;
    document.getElementById("lat").value=lat; 
    lng=position.coords.longitude;
    document.getElementById("lng").value=lng;	
    latlong=new google.maps.LatLng(lat,lng);
    geocoder.geocode({'latLng': latlong}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          document.getElementById("address").value=results[1].formatted_address;
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });    
    map.setCenter(new OpenLayers.LonLat(lng, lat), 9);
    map.addControl(new OpenLayers.Control.LayerSwitcher());    
  }
  function showError(error)
  {
    switch(error.code) 
    {
      case error.PERMISSION_DENIED:
        alert("User denied the request for Geolocation.")
        break;
      case error.POSITION_UNAVAILABLE:
        alert("Location information is unavailable.")
        break;
      case error.TIMEOUT:
        alert("The request to get user location timed out.")
        break;
      case error.UNKNOWN_ERROR:
        alert("An unknown error occurred.")
        break;
    }
    lat=-6.9833333;
    lng=108.48333330000003;
    latlong=new google.maps.LatLng(lat,lng);
    geocoder.geocode({'latLng': latlong}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          document.getElementById("address").value=results[1].formatted_address;
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });    
    map.setCenter(new OpenLayers.LonLat(lng, lat), 9);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
  }  
  function codeLatLong(lat,lng){
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          document.getElementById("address").value=results[1].formatted_address;
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });    
  }
  function codeAddress() {
    var address = document.getElementById('address').value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        latlong=results[0].geometry.location;
        lat=latlong.lat();
        lng=latlong.lng();
        document.getElementById("lat").value=lat;
        document.getElementById("lng").value=lng;
        map.setCenter(new OpenLayers.LonLat(lng,lat),9);
        show_location(document.getElementById("commodity").value);
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }  
  function show_location(str)
  {
    var xmlhttp;    
    if (str == "")
    {
      document.getElementById("loc_detail").innerHTML="";
      return;
    }
    if (window.XMLHttpRequest)
    {
      xmlhttp=new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        document.getElementById("loc_detail").innerHTML=xmlhttp.responseText;
        distribution('georss.php?q='+str);
      }
    }
    lat=document.getElementById("lat").value;
    lng=document.getElementById("lng").value
    xmlhttp.open("GET","location.php?q="+str+"&lat="+lat+"&lng="+lng,true);
    xmlhttp.send();
  }  
  function distribution(str) 
  {
     if(map.getNumLayers()>1)
      map.removeLayer(geolayer);
     geolayer = new OpenLayers.Layer.GeoRSS("GeoRSS", str);
     map.addLayer(geolayer);
  }
</script>                                
</body>
</html>

//-- namafile :location.php
<?php
$id_commodity=isset($_GET["q"])?$_GET["q"]:'';
$lat=isset($_GET["lat"])?$_GET["lat"]:'0';
$lng=isset($_GET["lng"])?$_GET["lng"]:'0';
include "db.config.php";
$sql="SELECT
        a.location_name,a.lat,a.lng,
        ( 6371 
        * acos(cos(radians($lat))
        * cos(radians(a.lat))
        * cos(radians(a.lng) - radians($lng))
        + sin(radians($lat))
        * sin(radians(a.lat)))
        ) AS distance
     FROM 
        tbl_location a
        JOIN rel_loc_commodity b USING(id_loc)
     WHERE 
        b.id_commodity = '".$id_commodity."'
     ORDER BY 
        distance";
?>
<table id='tablelokasi'>
  <tr>
    <th>Location</th>
    <th>Latitude &deg</th>
    <th>Longitude &deg</th>
    <th>Distance</th>
  </tr>
  <?php
  if($result = $db->query($sql))
  {
    $i=0;
    while($record = $result->fetch_object())
    {
      echo " <tr>"
          ." <td>".$record->location_name."</td>"
          ." <td> <input type='text' size='7' id ='lat".++$i."' name='lat[]' value='".$record->lat."'></td>"
          ." <td> <input type='text' size='7' id ='lon".$i."' name='lng[]' value='".$record->lng."'></td>"
          ." <td id='result'>".number_format($record->distance,2)." Km</td>"
          ." </tr>n";
    }
  }
  ?>
</table>

//-- namafile : georss.php
<?php
header("Content-Type: text/xml");
$out="<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/css/rss.css" ?>
<rdf:RDF  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns="http://purl.org/rss/1.0/"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:georss="http://www.georss.org/georss">"; 
include "db.config.php";
$sql="SELECT a.location_name,a.lat,a.lng
      FROM tbl_location a
      JOIN rel_loc_commodity b USING(id_loc)
      WHERE 1 "
     .(isset($_GET['q'])?" AND b.id_commodity='".urldecode($_GET['q'])."'":"");
if($result=$db->query($sql))
{
  while($record=$result->fetch_object())
  {
    $out.="
<item >
<link>#</link>
<title>{$record->location_name}</title>
<description><![CDATA[ Description here ]]></description>
<georss:point>{$record->lat}  {$record->lng}</georss:point>
</item>n";
  }    
}
echo $out;
?>
</rdf:RDF>