BloggerAds

2011年6月13日 星期一

Google Map JavaScript API v3 的一些常用語法

下列是使用Google Map API時的一些常用的語法

1. Google Map  初始化:
先 include google map api
<script type="text/javascript"src="http://maps.google.com/maps/api/js?sensor=false" ></script>
接著在Body中加入下面這個Div,這個Div是要用來顯示Google Map的物件
<div id="map_canvas" style="width:300px;height:300px;"></div>
接著加入下面的JavaScript程式碼,可以 寫在body的onload事件 或 jQuery的 $(document).ready 中
var latlng = new google.maps.LatLng(23.69781, 120.96051499999999);  //台灣座標
var myOptions = {
    zoom: 15,    //地圖縮放比例,數字越大,路越大
    center: latlng,  //地圖的中心座標
    mapTypeId: google.maps.MapTypeId.ROADMAP  //地圖型態,可參考 這裡
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
2. 新增Marker:
var myLatlng = new google.maps.LatLng(23.69781, 120.96051499999999);
var marker = new google.maps.Marker({
    position: myLatlng,    //Marker的座標
    map: map,    //map物件,以這篇文章的例子,就是上面那個map物件
    title: 'title'    //當滑鼠移至Marker上時,要顯示的Title文字
});
3. 在Marker click時,顯示InfoWindow:
google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
});
4. 新增InfoWindow:
var infowindow = new google.maps.InfoWindow();    //初始一個物件
infowindow.setContent('這是內容');    //InfoWindow的內容,可用Html語法
infowindow.setPosition(myLatlng);    //座標
5. 在地圖Click時新增一個Marker:
google.maps.event.addListener(map, "click", function(event) {
    marker_Click = new google.maps.Marker({
                    map: map,
                    position: event.latLng
                });
            });
6. 用地址查座標:
function getLatLngByAddr() {
    var geocoder = new google.maps.Geocoder();  //定義一個Geocoder物件
    geocoder.geocode(
        { address: '[地址]' },    //設定地址的字串
        function(results, status) {    //callback function
            if (status == google.maps.GeocoderStatus.OK) {    //判斷狀態
                alert(results[0].geometry.location);             //取得座標                                
            } else {
                alert('Error');
            }
      }
 );
}

參考:
http://itunes.apple.com/us/app/wikihow-how-to-diy-survival/id309209200?mt=8
Google Map Reference
Google Map API Tutorial

3 則留言:

  1. 請問如何利用 經緯度轉地址呢
    我抓得到經緯度但是不會轉成中文

    回覆刪除
  2. 用同樣的方式可行,只是傳入的是location,可試試下列程式碼
    ex.
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ location: new google.maps.LatLng(23.69781, 120.96051499999999) },
    function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    alert(results[0].formatted_address);
    }
    }
    );

    回覆刪除
  3. 大大不好意思:
    想請問一下 如果在WEB 上實際做這一塊,有辦法抓到目前所在位置的座標嗎?
    我想要地圖一開始就在使用者附近這樣@_@

    回覆刪除