LoginSignup
16
20

More than 5 years have passed since last update.

位置情報をささっと取得したい

Last updated at Posted at 2016-08-14

たまに使うけど、忘れてて毎回自分のリポジトリを調べるので、まとめておく。

位置情報をさっと取得したい

kl.location.js
// -------------------------
// HTML5での位置情報取得を少しだけ楽にする
// 2016.07 @ZrelyyDereva
// License: MIT 
// -------------------------
(function(global) {
    //ブラウザ以外では使わない
    if (!("document" in global)) return;
    global.$kl = global.$kl || {};

    global.$kl.messages = global.$kl.messages || {};
    global.$kl.messages.LOCATION_ERROR_NOT_SUPPORTED = "サポートされていません";
    global.$kl.messages.LOCATION_ERROR_NOT_ALLOWED = "利用が許可されていません";
    global.$kl.messages.LOCATION_ERROR_NOT_SUPPLIED = "デバイスの位置が判定できません";
    global.$kl.messages.LOCATION_ERROR_TIMED_OUT = "タイムアウトしました";
    global.$kl.messages.LOCATION_ERROR_OTHER = "その他のエラー";
    global.$kl.consts = global.$kl.consts || {};
    global.$kl.consts.LOCATION_API_KEY = "";//※位置情報→住所変換のための、GoogleのAPIキー

    var s = function(callback) {
        var _callback = callback;
        return function getlocationsuccess(position) {
            var latlng = position.coords.latitude + "," + position.coords.longitude;
            _callback({
                latlng: latlng,
            });
            var latlng = position.coords.latitude + "," + position.coords.longitude;
            var uri = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&key=" + global.$kl.consts.LOCATION_API_KEY;
            if (!$kl.ajax) {
                _callback = null;
                return
            };
            $kl.ajax({
                url: uri,
                method: "GET"
            }, function(r) {
                var r2 = JSON.parse(r);
                var addr = ""
                if (r2.results && r2.results[0]) {
                    addr = (r2.results[0].formatted_address).replace("日本, ", "");
                }
                _callback({
                    latlng: latlng,
                    address: addr
                });
                _callback = null;
            });
        }
    }
    var f = function(callback) {
        var _callback = callback;
        return function locationfaiulre(params) {
            switch (error.code) {
                case 1:
                    _callback(global.$kl.messages.LOCATION_ERROR_NOT_ALLOWED);
                    break;
                case 2:
                    _callback(global.$kl.messages.LOCATION_ERROR_NOT_SUPPLIED);
                    break;
                case 3:
                    _callback(global.$kl.messages.LOCATION_ERROR_TIMED_OUT);
                    break;
                default:
                    _callback(global.$kl.messages.LOCATION_ERROR_OTHER);
            }
            _callback = null;
        }
    }

    global.$kl.getLocation = function getLocation(success, failure) {
        if (!global.navigator) return failure(global.$kl.messages.LOCATION_ERROR_NOT_SUPPORTED);
        try {
            global.navigator.geolocation.getCurrentPosition(s(success), f(failure));
        } catch (e) {
            return failure(global.$kl.messages.LOCATION_ERROR_OTHER);
        }
    }
})((this || 0).self || global);

これを読み込んでおけば、$kl.getLocation で緯度経度、あれば住所が割とサクッと取得できて便利です。
\$kl.ajaxに関しては、私のリポジトリのどのフォルダにもあると思いますが、要は\$.ajaxみたいなものなので、適当にjQuery準拠に直してお試しください。

08.15 19:00追記
あんまり同じ位置に対して位置情報を求めても申し訳ないのと、クロスドメインの関係で面倒なこともあったので、位置情報はこんなPHP作ってます

geocode.php
<?php

//-8<-8<-8<-8<-8M-8<-8<
// snipped 共通関数とJWTで認証 
//->8->8->8->8->8->8->8

$apikey = "xxxxxxx"; //APIのキー
$db = "geocodes";

if(!isset($_GET['latlng'])){
    json_error("latlng required");
}
$latlng = isset($_GET['latlng'])?$_GET['latlng']:"";

$pdo = _db_connect_one($db);

try {
    $tmp = db_execute_one($db,"select latlng from geocodes limit 1",$pdo);
} catch (Exception $er){
    if(strpos($er->getMessage(),'no such table') !== false){
        $tmp = db_execute_one($db,"CREATE TABLE geocodes(
            latlng TEXT primary key,
            data TEXT
            ) ",$pdo);
    }else{
        json_error($er);
    }
}

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');

$tmp = db_execute_one($db,"select data from geocodes where latlng='".urlencode($latlng)."'",$pdo);
//print_r($tmp);
if(count($tmp)==0){
    $uri = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlng . "&key=". $apikey ."&language=ja";
    $data = file_get_contents($uri);
    $sql = "insert into geocodes (latlng,data) values (?,?);";
    $tmp = db_executequery_one($db,$sql,$pdo,[urlencode($latlng),$data]);  
}
$tmp = db_execute_one($db,"select data from geocodes where latlng='".urlencode($latlng)."'",$pdo);

echo @$tmp[0]['data'];

?>
16
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
20