將中文地址寫入資料庫時透過 google maps 取得作標

edited 十月 2013 in 原創軟體分享區
1. 送出畫面
<form method="post" ..略...
<input name="address" value="" />

2. 接收的 php

$address = $_POST;
$map_api_key = 申請的 google maps API;

$csv_url = "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&key=".$map_api_key;

$ch = curl_init($csv_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$get_contents = curl_exec($ch);
curl_close($ch);

$string = explode(',', $get_contents);

$longitude = $string[2]; // 經度

$latitude = $string[3]; // 緯度

$sql = ...把地址跟經緯度都寫入資料庫...

原始討論: http://twpug.net/x/modules/newbb/viewtopic.php?topic_id=3592

評論

  • edited 八月 2008
    1. 準備一個資料表 address_book
    CREATE TABLE `address_book` (
    `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
    `title` VARCHAR( 255 ) NOT NULL COMMENT '標題',
    `address` VARCHAR( 255 ) NOT NULL COMMENT '地址',
    `longitude` FLOAT( 10, 6 ) NOT NULL COMMENT '經度',
    `latitude` FLOAT( 10, 6 ) NOT NULL COMMENT '緯度',
    PRIMARY KEY ( `id` )
    ) ENGINE=MyISAM;;


    2. 送出畫面
    <form method="post" ..略...
    <input name="address" value="" />


    3. 接收的 php
    <?php
    $address = $_POST;
    $map_api_key = 申請的 google maps API;

    $csv_url = "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&key=".$map_api_key;
    $ch = curl_init($csv_url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $get_contents = curl_exec($ch);
    curl_close($ch);
    $string = explode(',', $get_contents);
    $longitude = $string[2]; // 經度
    $latitude = $string[3]; // 緯度

    // 把地址跟經緯度都寫入資料庫
    // ...以下略...
    ?>


    4. 瀏覽某一筆 address_book 資料的 php --> address.php?id=xxx

    <?php
    $id = $_GET;
    // ....撈出這筆 id 的地址 過程略
    $address = $book;
    $map_api_key = 申請的 google maps API;
    $smarty->assign('google_maps_js', load_google_maps($map_api_key, $address));

    function load_google_maps($map_api_key, $address) {
    $gmap_js = '
    <!-- Google Maps Mashup -->
    <script type="text/javascript" src="http://www.google.com/jsapi?key='.$apikey.'"></script>;
    <script type="text/javascript">
    google.load("maps", "2", {"locale" : "zh_TW"}); // 引入 maps api 、設定介面語系為正體中文
    function initialize() {
    //if (GBrowserIsCompatible()) { 判斷瀏覽器是否支援 google maps
    var map = new google.maps.Map2(document.getElementById("map"));
    var geocoder = new GClientGeocoder(); // 地理編碼解譯
    var address = "'.$address.'";
    map.addControl(new GSmallMapControl());
    map.addControl(new GOverviewMapControl());
    geocoder.getLatLng(address, function(point) {
    if (!point) {
    alert("Google Maps 找不到該地址,無法顯示地圖!"); // 如果Google Maps無法顯示該地址的警示文字
    } else {
    map.setCenter(point, 16);
    /* 暫訂 */
    var marker = createMarker(point, "'.$address.'");
    map.addOverlay(marker);

    var bounds = map.getBounds();
    // 西南座標
    var southWest = bounds.getSouthWest();
    // 東北座標
    var northEast = bounds.getNorthEast();
    // 地圖四角座標
    var lng1 = northEast.lng();
    var lng2 = southWest.lng();
    var lat1 = northEast.lat();
    var lat2 = southWest.lat();
    // 除錯
    //document.getElementById("debug").innerHTML = "xml.php?lng1="+ lng1 +"&lng2="+ lng2 +"&lat1="+ lat1 +"&lat2="+ lat2;
    GDownloadUrl("xml.php?lng1="+ lng1 +"&lng2="+ lng2 +"&lat1="+ lat1 +"&lat2="+ lat2, function(data, responseCode) {
    if(responseCode == 200) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
    var lat = parseFloat(markers.getAttribute("lat"));
    var lng = parseFloat(markers.getAttribute("lng"));
    var point = new GLatLng(lat,lng);
    var title = markers.getAttribute("title");
    //var address = markers.getAttribute("title");
    //var title = markers.getAttribute("title");
    var marker = createMarker(point, title);
    map.addOverlay(marker);
    }
    } else if(responseCode == -1) {
    alert("Data request timed out. Please try later.");
    } else {
    alert("Request resulted in error. Check XML file is retrievable.");
    }
    });

    }
    });
    }
    function createMarker(point, title) {
    var marker = new GMarker(point);
    var html = "<p><small>" + title + "</small></p>";
    GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
    });
    return marker;
    }
    google.setOnLoadCallback(initialize);
    </script>
    ';
    return $gmap_js;
    }

    $smarty->display('show_map.html');

    ?>



    5. xml.php
    取得地圖四角座標 撈出符合作標範圍內的資料
    產生為 XML 再送給 google maps

    <?php
    require 'header.php';
    $lng1 = $_GET;
    $lng2 = $_GET;
    $lat1 = $_GET;
    $lat2 = $_GET;

    $sql = 'SELECT id, title, latitude, longitude FROM 'address_book' WHERE (longitude < '.$lng1.' AND longitude > '.$lng2.') AND (latitude < '.$lat1.' AND latitude > '.$lat2.')';
    //echo $sql;
    $result = $DB->query($sql);
    $item = array();
    echo '<markers>';
    while($xml = $DB->fetchArray($result)) {
    echo '<marker lat="'.$xml.'" lng="'.$xml.'" title="'.$xml.'" />';
    }
    echo '</markers>';
    ?>


    6. 移動地圖時重新載入 xml.php
    這個重責大任就交給你了 好嗎?
  • edited 八月 2008
    感謝提供 :)

    我的作法是在使用者檢視特定資料時才透過 Google 查詢座標,如果取得座標就同時存到資料庫,藉此避免短時間的大量請求造成 Google 停權。

    js:
    if (!point) {
                  Element.replace($("map"), '這個地址 Google 說不知道,所以沒辦法顯示地圖!');
                } else {
                  map.setCenter(point, 16);
                  var marker = new GMarker(point);
                  map.addOverlay(marker);
                  marker.openInfoWindowHtml(title);
                  new Ajax.Request('xxx.php', {
                  	method: 'post',
                  	parameters: { dataPoint:point, dataId:id }
                  });
                }
    

    php:
    $string = trim($this->params['form']['dataPoint']);
    	        $string = substr($string, 1, -1);
    	        $dataArray = explode(',', $string);
    	        $this->data['Hotel']['id'] = intval($this->params['form']['dataId']);
    	        $this->data['Hotel']['latitude'] = trim($dataArray[0]);
    	        $this->data['Hotel']['longitude'] = trim($dataArray[1]);
    	        $this->Hotel->save($this->data);
    

    只是在 PHP 端會做額外的來源檢查,避免有人亂試 ^^
  • edited 十二月 2009
    $csv_url = "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&key=".$map_api_key;

    这个不行,不知道为什么
Sign In or Register to comment.