GoogleはGoogle AJAX Search APIというものを公開しており、これを利用することで、Googleのサービスを自分のWebアプリに組み込むことができます。また、Google AJAX Search APIはAPIキーの登録がいらないようなので、気軽に使えます。
Google AJAX Search APIにはクライアントの国・都道府県・市町村などの住所に近い情報を得ることができる機能があります。結構楽しいので、使い方を紹介します。
1. google.loader.ClientLocationオブジェクト
google.loader.ClientLocationpオブジェクトはアプリケーションがAJAX API ローダーを使用した場合に生成されるといったことが公式ドキュメントには書かれています。要するにgoogle.loader.ClientLocationがさまざまな位置情報をもっているので、それを参照すれば、位置情報を取得できるという話です。
ちなみに、クライアントのIPアドレスから位置情報が割り出せなかった場合は、google.loader.ClientLocationはnullになります。
2. google.loader.ClientLocationのプロパティ
google.loader.ClientLocationオブジェクトが生成されると、次のプロパティが読み込まれるようです。
・ClientLocation.latitude:緯度
・ClientLocation.longitude:経度
・ClientLocation.address.city:市町村
・ClientLocation.address.country:国
・ClientLocation.address.country_code:国名コード
・ClientLocation.address.region:都道府県
3. 使用例
「位置を取得」ボタンを押すと、テキストボックスに位置情報が表示されます。
<html>
<head>
<title>Google AJAX Search API</title>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
<!--
function getAddress() {
if ( google.loader.ClientLocation == null ) {
alert("位置情報の取得に失敗しました。");
}
document.getElementById("country").value = google.loader.ClientLocation.address.country;
document.getElementById("region").value = google.loader.ClientLocation.address.region;
document.getElementById("city").value = google.loader.ClientLocation.address.city;
document.getElementById("latitude").value = google.loader.ClientLocation.latitude;
document.getElementById("longitude").value = google.loader.ClientLocation.longitude;
}
-->
</script>
</head>
<body>
国名:<input type="text" id="country" /><br />
都道府県:<input type="text" id="region" /><br />
市区町村:<input type="text" id="city" /><br />
緯度:<input type="text" id="latitude" /><br />
経度:<input type="text" id="longitude" /><br />
<input type="button" onclick="getAddress()" value="位置を取得" />
</body>
</html>
<head>
<title>Google AJAX Search API</title>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
<!--
function getAddress() {
if ( google.loader.ClientLocation == null ) {
alert("位置情報の取得に失敗しました。");
}
document.getElementById("country").value = google.loader.ClientLocation.address.country;
document.getElementById("region").value = google.loader.ClientLocation.address.region;
document.getElementById("city").value = google.loader.ClientLocation.address.city;
document.getElementById("latitude").value = google.loader.ClientLocation.latitude;
document.getElementById("longitude").value = google.loader.ClientLocation.longitude;
}
-->
</script>
</head>
<body>
国名:<input type="text" id="country" /><br />
都道府県:<input type="text" id="region" /><br />
市区町村:<input type="text" id="city" /><br />
緯度:<input type="text" id="latitude" /><br />
経度:<input type="text" id="longitude" /><br />
<input type="button" onclick="getAddress()" value="位置を取得" />
</body>
</html>