如今,許多應用都提供地理位置定位的功能,只要用戶開放他們的位置信息就能夠實現定位了,今天咱們將建立一個基於Google 地圖的微博用戶地圖,這裏咱們將經過Weibo API獲取微博用戶的地理信息,而後使用Google地理位置服務將用戶的地理信息轉換爲相應的地理座標,最後,根據地理座標加載到Google地圖中顯示。javascript
首先,咱們定義程序的Index頁面,它用於加載顯示Google地圖,具體實現以下:css
<!-- Weibo user map --> <div id="map"></div> <div class="weibo"> <div class="inside"></div> </div> <div class="posts"></div> <div class="get"> <input type="hidden" value="優等生杜小明" /> <input type="hidden" value="楊冪" /> <input type="hidden" value="思想匯聚人生" /> <input type="hidden" value="KevinOriste" /> <input type="hidden" value="韓寒" /> <input type="hidden" value="復古老照片" /> <input type="hidden" value="獨立檢察官2011" /> <input type="hidden" value="顧扯淡" /> <input type="hidden" value="李開復"/> </div>
上面,第一個div(map)用來加載顯示Google 地圖,第二個div(weibo)用來顯示微博用戶的頭像、描述、用戶名和我的信息,第三個div(posts)用來加載顯示相應用戶最近發的微博信息,最後,一個div(get)用來存放微博用戶名,咱們的程序將根據這些用戶名來獲取相應的微博數據。html
接下來,咱們經過jQuery插件方式實現微博用戶地圖插件,咱們定義了三個方法別是:weiboMap(),weiboMap.size()和weiboMap.init(),具體定義以下:java
// Weibo user map plugin. (function($) { $.fn.weiboMap = function(options) { // Your code here. }; $.fn.weiboMap.size = function() { // Your code here. }; $.fn.weiboMap.init = function() { // Your code here. }; })(jQuery);
weiboMap()方法經過調用微博API獲取微博數據,而後將返回數據加載顯到Index頁面中;weiboMap.size()獲取當前窗口的大小,用來設置Google地圖的初始大小;weiboMap.init()初始化Google地圖,設置地圖的zoom,地圖中心位置(這裏以北京爲中心),地圖大小和地圖類型。git
上面,咱們只給出了三個方法的定義,但尚未給出具體的實現,接下來讓咱們實現上面的方法吧!github
// Gets the size of window . $.fn.weiboMap.size = function() { var w = $(window).width(), h = $(window).height(); return { width: w, height: h }; }
上面,咱們實現了weiboMap.size()方法,它獲取當前窗口的大小,而後返回一個包含長和寬屬性的對象。web
// Initalizes the google map $.fn.weiboMap.init = function() { // Sets the size of map. var size = $.fn.weiboMap.size(); $('#map').css({ width: size.width, height: size.height }); // Creates a google map instance. map = new google.maps.Map(document.getElementById('map'), $.fn.weiboMap.defaults.data); // Creates a geo coder instance. geocoder = new google.maps.Geocoder(); }
圖1 Google地圖ajax
咱們經過方法weiboMap.init()初始化Google地圖,首先,咱們設置了map div的長和寬,而後建立了Google地圖和地理編碼對象。json
在建立新的地圖實例時,咱們須要在網頁中指定一個 div 元素做爲地圖的容器;這裏咱們經過getElementById ()方法獲取map元素。api
構造函數:Map(mapDiv:Node, opts?:MapOptions)
說明:第一個參數設置地圖的HTLM容器,第二參數可選,用於設置Google地圖的zoom,顯示位置,地圖大小和地圖類型等(具體請參考這裏)。
上面,咱們實現了方法weiboMap.size()和weiboMap.init(),接下來咱們繼續實現方法weiboMap()。
因爲weiboMap()負責調用微博API獲取微博數據,而後加載顯示到Google地圖上面,因此這裏就涉及到兩個功能的實現:調用微博API和Google地圖地理定位。
首先,咱們定義方法getUsers()獲取在Index.html頁面中設置的微博用戶名,而後根據這些用戶名獲取相應的用戶信息和微博信息。
// Gets the list of weibo screen name // from the .get div. function getUsers() { var arr = new Array(); $('.get').find('input').each(function(i) { var $element = $(this); arr[i] = $element.val(); }); return arr; }
上面,咱們經過find()方法獲取get元素中的用戶名,而後儲存在數組中而且返回該數組,接下來,咱們實現show()方法,它根據微博用戶名調用微博API獲取用戶的基本信息和微博信息,因爲用戶的基本信息包含了地理信息,咱們經過Google的地理編碼服務將用戶的地理信息轉換爲地理座標,例如:根據北京轉換爲相應的經緯度北緯39.90,東經116.41,具體實現以下:
// Get weibo user show and binding data // with google map. function show() { // Gets the weibo user screen name. var users = getUsers(); for (var i = users.length - 1; i >= 0; i--) { // Invokes the weibo api to get data. $.getJSONP({ url: opts.url, timeout: 30000, data: { source: opts.appKey, access_token: opts.accessToken, screen_name: users[i] }, error: function(xhr, status, e) { console.log(e); }, complete: function() { }, success: function(json) { if (json.data.error) { // log the error. return; } var arr = new Array(), img = json.data.profile_image_url, screen_name = json.data.screen_name; // Initalizes the geo coder instance. geocoder.geocode({ address: json.data.location }, function(response, status) { if (status == google.maps.GeocoderStatus.OK) { // Sets latitude and longitude by location name. var x = response[0].geometry.location.lat(), y = response[0].geometry.location.lng(), blogUrl, marker = new google.maps.Marker({ icon: img, map: map, title: screen_name, animation: google.maps.Animation.DROP, position: new google.maps.LatLng(x, y) }); // Creates user information. blogUrl = json.data.url !== '' ? json.data.url : 'http://www.weibo.com/u/' + json.data.id; arr.push('<div class="item">'); arr.push('<p class="img"><a href="#" class="open" rel="' + screen_name + '"><img src="' + img + '" alt="" /></a></p>'); arr.push('<div class="entry">'); arr.push('<a href="#" class="open title" rel="' + screen_name + '">' + json.data.name + '</a>'); arr.push('<p class="description">' + json.data.description + '</p>'); arr.push('<p class="url"><a href="' + blogUrl + '" target="_blank">' + blogUrl + '</a></p>'); arr.push('<p class="count">粉絲: ' + json.data.followers_count + ', 關注: ' + json.data.friends_count + '</p>'); arr.push('</div>'); arr.push('</div>'); var html = arr.join(''); arr = []; $('.weibo').find('.inside').append(html); // Clicks the user image showing relative user's weibo. google.maps.event.addListener(marker, 'click', function() { open(this.title); }); } }); } }); }; }
上面,咱們經過getJSONP()方法調用微博API獲取微博用戶數據,如名稱,描述,地理位置和頭像路徑等,而後,咱們使用Google的地理編碼服務將用戶地理位置信息轉換爲具體的地理座標,最後,咱們將微博用戶的頭像加載到地圖的相應座標上而且添加用戶的名稱和描述信息。
接着,咱們打開Chrome的開發者工具,在Network中,查看到getJSONP()方法經過向微博的users/show接口發送請求來獲取微博數據。
圖2 Ajax請求
當請求成功微博將返回JSON格式的數據,數據的結構以下:
圖3 微博JSON數據
前面,咱們取得了微博數據,咱們根據用戶的location值獲取相應的地理座標值,這裏咱們使用Google的地理編碼服務能夠將用戶地理位置信息(location)轉換爲具體的地理座標,具體實現以下:
// Sets latitude and longitude by location name. var x = response[0].geometry.location.lat(), y = response[0].geometry.location.lng(), blogUrl, marker = new google.maps.Marker({ icon: img, map: map, title: screen_name, animation: google.maps.Animation.DROP, position: new google.maps.LatLng(x, y) });
咱們根據用戶的微博頭像,名稱和地理座標建立marker實例,它用於在地圖上顯示對應的微博用戶的位置,而後,咱們把用戶的名稱,描述,粉絲和關注數量加載到weibo div中。
圖4 微博用戶地圖
上面,咱們實現了根據微博用戶的位置信息進行地理定位,這樣咱們能夠在地圖上查看到每一個微博用戶的地理位置了,在地圖的下方,咱們給出了微博用戶的描述信息。
如今,咱們已經實現了微博用戶地圖的功能了,隨着,咱們查詢用戶增長,但咱們顯示用戶信息的空間是有限,難道咱們要用整個窗口來顯示用戶的信息嗎?
其實,咱們能夠經過滾動方式來查看微博用戶的信息,具體實現以下:
// Gets mouse Y coordinate. function getYCoordinate(e) { var y = e.pageY; return y; } // Checks move size. function checkYCoordinate(y) { var all = $('.weibo').height(), inside = $('.weibo').find('.inside').height(); // The max move size |all - inside|. if (y < (all - inside)) { y = all - inside; } else if (y > 0) { y = 0; } return y; } // Updates inside top css. function update(e) { var y = getYCoordinate(e), movey = y - my, // Changes Y coordinate. top = ey + movey, check = checkYCoordinate(top); console.log(top, check); $('.weibo').find('.inside').css({ top: check + 'px' }); } init(); function init() { $('.weibo').find('.inside').bind({ mousedown: function(e) { e.preventDefault(); mouseDown = true; var mouseY = getYCoordinate(e), // Gets element coordinate. element = $(this).position(); // Gets Y coordinate move. my = mouseY; ey = element.top; update(e); }, mousemove: function(e) { if (mouseDown) update(e); return false; }, mouseup: function() { if (mouseDown) mouseDown = false; return false; }, mouseleave: function() { if (mouseDown) mouseDown = false; return false; } }); }
用戶經過垂直拖拉weibo div來實現上下查看微博用戶信息,首先init()方法綁定了mousedown,mousemove,mouseup和mouseleave事件,當用戶點擊weibo div區域時,調用getYCoordinate()方法獲取鼠標當前的Y座標,當用戶拖動鼠標時,調用update()方法更新inside div的top屬性。
如今,咱們能夠經過垂直拖拉查看微博用戶的信息,接下來,咱們添加CSS效果調整一下界面佈局,具體實現以下:
@import url("reset.css"); /* ------ layout -----------------------------------------------*/ html, body { margin:0; padding:0; } body { font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#333; line-height:18px; } #map { float:left; } .weibo { position:fixed; left:0; bottom:0; background:#000; background:rgba(0, 0, 0, .7); width:100%; height:180px; color:#fff; overflow:hidden; } .weibo .inside { position:absolute; top:0; left:0; cursor:n-resize; } .weibo .item { float:left; width:280px; padding:20px; } .weibo .item .img { float:left; width:48px; } .weibo .img img { -moz-box-shadow:0 0 5px #000; -webkit-box-shadow:0 0 5px #000; box-shadow:0 0 5px #000; } .weibo .item .entry { float:right; width:215px; height:140px; color:#eee; font-size:11px; position:relative; } .weibo .item .count { position:absolute; left:0; bottom:-10px; font-size:10px; text-transform:uppercase; } .weibo .item .title { font-size:13px; font-weight:bold; color:#fff; } .weibo .item .url a { text-decoration:underline; } .weibo .item p { margin-bottom:5px; } .posts { display:none; position:absolute; left:50%; margin-left:-310px; width:580px; bottom:180px; background:#fff; color:#fff; background:#000; background:rgba(0, 0, 0, .7); padding:20px; } .posts .post { float:left; clear:both; width:100%; margin-bottom:20px; font-size:12px; font-weight:bold; } /* ------ anchors -----------------------------------------------*/ a { text-decoration:none; color:#fff; }
圖5 微博用戶地圖
上面,實現了微博用戶地圖,咱們能夠在Google地圖上查看到微博用戶對應的地圖位置,在下面給出了每一個用戶的描述信息。
咱們實現了微博用戶地圖程序,首先將Google地圖加載程序當中,而後,咱們經過ajax請求調用微博API,獲取微博用戶的基本信息,當成功返回JSON數據時,從中獲取用戶的地址信息,而後經過Google的地理編碼服務將地址信息轉換爲地理座標,這樣咱們就能夠定位每一個微博用戶的地理位置了,最後,經過marker把每一個用戶的定位到Google地圖上顯示出來。