Page 90 - JavaScript修炼之道
P. 90

任务35  获得地理位置及该位置的照片                 81


                   获取给定文本的地理位置

                  (以下代码实际上假设只有第一个地理位置结果有用。)

                    mashups/geo/geo.js

                   // 在你自己的代码中用你自己的API码 :-)
                   var YAHOO_APPID = 'KwWEZW_V34GVYNWWOLZm6NT.' +
                     'XfIwNrF9ysko8qu6sDuE6SbehuptUZQp6jKF130V25hFTMrrdrbQeo4-';

                   function getGeoLocationFor(text) {
                     Placemaker.config.appID = YAHOO_APPID;
                     $('indicator').addClassName('loading').update('Getting geolocation for ' +
                       text.escapeHTML() + '...').show();
                     Placemaker.getPlaces(text, function(places) {
                       if (places.error) {
                         $('indicator').removeClassName('loading').
                           update(places.error.escapeHTML());
                       } else {
                         var loc = (places.matches || [places.match])[0].place;
                         $('indicator').update('Loading ' + loc.name +
                           ' pics (' + loc.type + ')...');
                         getGeoPhotos(loc.centroid.latitude, loc.centroid.longitude);
                       }
                     }, 'en-US');
                   }

                   从Flickr获取指定地理位置的照片

                    mashups/geo/geo.js

                   // flickrCallback非常类似于Flickr同步任务的代码
                   // 在http://pragprog.com/titles/pg-js/source_code这个网址上获得完整的示例代码

                   function getGeoPhotos(lat, lon) {
                     $('indicator').addClassName('loading').show();
                     var uri = FLICKR_ENDPOINT + '?' + Object.toQueryString({
                       method: 'flickr.photos.search', api_key: FLICKR_API_KEY,
                       extras: 'date_taken,url_sq,description', lat: lat, lon: lon,
                       per_page: 50, format: 'json', jsoncallback: 'flickrCallback'
                     });
                     document.documentElement.firstChild.appendChild(
                       new Element('script', { type: 'text/javascript',
                         src: uri + '&r=' + Math.random() }));
                   }
   85   86   87   88   89   90   91   92   93   94   95