2012年6月21日木曜日

WebAPIの利用(5)

WebAPIの利用(4)を更に発展させ,ユーザーが入力した任意の文字列から座標を検索し,地図を表示する.

1.ユーザーが文字列を入力する画面(map_form.html)を用意.
2.画面に配置された送信ボタンを押すことで,postメソッドにより文字列を送信.
3.送信された文字列をphpファイル(map_xmlParse2.php)で受け取り.
4.受け取った文字列を用いて,マッチする座標を検索
5.座標を使って地図を表示.

表示例

LINK

map_form.html
<html>
<head>
 <title>form sample</title>
</head>
<body>
 <form action="map_xmlParse2.php" method="post">
  座標を調べたい文字列 : <input type="text" name="word" />
  <input type="hidden" name="sensor" value="true" />
  <input type="submit" />
 </form>
</body>
</html>

map_xmlParse2.php
<?php
 $word = htmlspecialchars($_POST['word']);
 $sensor = htmlspecialchars($_POST['sensor']);
 $url = "http://maps.google.com/maps/api/geocode/xml";
 $url .= "?address=".$word."&sensor=".$sensor;
 $article = simplexml_load_file($url);

 $lat = $article->result->geometry->location->lat;
 $lng = $article->result->geometry->location->lng;

print<<<EOF
 <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>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
 <script type="text/javascript">
   function initialize() {
     var myLatlng = new google.maps.LatLng(
EOF;
 echo $lat;
 echo ", ";
 echo $lng;
print<<<EOF
     );

     var myOptions = {
       zoom: 15,
       center: myLatlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

     var marker = new google.maps.Marker({
       position: myLatlng,
       map: map,
       title:"
EOF;
 echo $word;
print<<<EOF
       "
     });
   }
 </script>
 </head>
 <body onload="initialize()">
   <div id="map_canvas"></div>
 </body>
 </html>
EOF;
?>

0 件のコメント: