2013-05-12 3 views
-3

Я работал над побочным проектом и попал в блокпост. Я могу выполнять поиск по тегам и отображать их результаты только в порядке, но я также хотел бы разместить данные ниже каждого изображения, в частности, информацию о местоположении. Я делаю это в Javascript и прокомментировал строки, которые, как мне кажется, нужно скорректировать, но с удалением отметок комментариев даже изображения не появляются. Какие-нибудь советы? Объект JSON распечатаны с помощью вызова Instagram возвращает эти данные:Получение данных о местоположении с изображения (Instagram/JS)

Object 
    - data: Array[20] 
    - 0: Object 
     + caption: Object 
     + comments: Object 
     created_time: "1334402906" 
     filter: "Nashville" 
     id: "169306311223447303_5913362" 
     - images: Object 
     + low_resolution: Object 
     - standard_resolution: Object 
      height: 612 
      url: "http://distilleryimage7.instagram.com/f3f8d7b2862411e19dc71231380fe523_7.jpg" 
      width: 612 
     + thumbnail: Object 
     + likes: Object 
      link: "http://instagr.am/p/JZfzFqtI8H/" 
      location: Object 
      tags: Array[1] 
      type: "image" 
      user: Object 

И мой код выглядит следующим образом:

// Instantiate an empty object. 
var Instagram = {}; 

// Small object for holding important configuration data. 
Instagram.Config = { 
    clientID: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 
    apiHost: 'https://api.instagram.com' 
}; 


// ************************ 
// ** Main Application Code 
// ************************ 
(function(){ 
    var photoTemplate, resource; 

    function init(){ 
    bindEventHandlers(); 
    photoTemplate = _.template($('#photo-template').html()); 
    } 

    function toTemplate(photo){ 
    photo = { 
     count: photo.likes.count, 
     avatar: photo.user.profile_picture, 
     photo: photo.images.low_resolution.url, 
     url: photo.link 
     //location: photo.location <--------------------------This line. 
    }; 

    return photoTemplate(photo); 
    } 

    function toScreen(photos){ 
    var photos_html = ''; 
    //var photos_location = ''; <------------------------This line. 

    $('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id) 
        .fadeIn(); 

    $.each(photos.data, function(index, photo){ 
     photos_html += toTemplate(photo); 
     //photos_location += toTemplate(photo); <-----------------This line. 
    }); 

    $('div#photos-wrap').append(photos_html); 
    //$('div#photos-wrap').append(photos_location) <------------------This line. 
    } 


    function generateResource(tag){ 
    var config = Instagram.Config, url; 

    if(typeof tag === 'undefined'){ 
     throw new Error("Resource requires a tag. Try searching for cherry blossoms."); 
    } else { 
     // Make sure tag is a string, trim any trailing/leading whitespace and take only the first 
     // word, if there are multiple. 
     tag = String(tag).trim().split(" ")[0]; 
    } 

    // Configures the URL to search for pictures that fit the tag description. 
    url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&client_id=" + config.clientID; 

    return function(max_id){ 
     var next_page; 
     if(typeof max_id === 'string' && max_id.trim() !== '') { 
     next_page = url + "&max_id=" + max_id; 
     } 
     return next_page || url; 
    }; 
    } 

    function paginate(max_id){ 
    $.getJSON(generateUrl(tag), toScreen); 
    } 

    function search(tag){ 
    resource = generateResource(tag); 
    $('.paginate a').hide(); 
    $('#photos-wrap *').remove(); 
    fetchPhotos(); 
    } 

    function fetchPhotos(max_id){ 
    $.getJSON(resource(max_id), toScreen); 
    } 

    function bindEventHandlers(){ 
    $('body').on('click', '.paginate a.btn', function(){ 
     var tagID = $(this).attr('data-max-tag-id'); 
     fetchPhotos(tagID); 
     return false; 
    }); 

    // Bind an event handler to the `submit` event on the form 
    $('form').on('submit', function(e){ 

     // Stop the form from fulfilling its destinty. 
     e.preventDefault(); 

     // Extract the value of the search input text field. 
     var tag = $('input.search-tag').val().trim(); 

     // Invoke `search`, passing `tag` (unless tag is an empty string). 
     if(tag) { 
     search(tag); 
     }; 

    }); 

    } 

    function showPhoto(p){ 
    $(p).fadeIn(); 
    } 

    // Public API 
    Instagram.App = { 
    search: search, 
    showPhoto: showPhoto, 
    init: init 
    }; 
}()); 


$(function(){ 
    Instagram.App.init(); 

    Instagram.App.search('takoyaki'); 
}); 
+0

У вас есть jsfiddle вашего кода? Вы посмотрели в консоли, чтобы узнать, какие у вас ошибки? – Xotic750

+0

http://jsfiddle.net/FNM7G/1/ - Хотя я где-то прищурился. Не мог вспомнить, что за сайт был для меня, так рада, что вы упомянули об этом. Благодаря! Я не совсем уверен в ошибках. – user2371067

+0

На самом деле я просто пытаюсь расшириться на этом сайте: http://grammy.eduvoyage.com/ Функциональность такая же, но я хочу извлечь дополнительную информацию из каждой фотографии. В какой-то момент я хочу взять эти идентификаторы местоположения и отобразить их на картах Google под изображением. – user2371067

ответ

1

Это работает, до тех пор, как фотография имеет данные о местоположении, не все из них сделать

CSS

body { 
    background: #e3e8ec url(http://grammy.eduvoyage.com/images/tile.png) repeat 50% 0; 
} 
#search { 
    height: 40px; 
    padding: 10px; 
    text-align: center; 
    position: fixed; 
    width: 240px; 
    margin: 0 auto; 
    z-index: 100; 
    left: 50%; 
    top: 0; 
    margin-left: -130px; 
    border-radius:0 0 5px 5px; 
} 

.search-wrap { 
    background: white; 
    line-height: 30px; 
    height: 30px; 
    text-align: left; 
    border-radius: 3px; 
    width: 230px; 
    margin: 0; 
    border: 1px solid #ddd; 
} 

#photos-wrap { 
    width: 810px; 
    margin: 70px auto 40px auto; 
    position: relative; 
    z-index: 1; 
} 

.photo .avatar { 
    width: 40px; 
    height: 40px; 
    padding: 2px; 
    position: absolute; 
    bottom: 11px; 
    right: 8px; 
    background: white; 
} 

.photo { 
    margin-bottom: 20px; 
    float: left; 
    position: relative; 
    width: 250px; 
    height: 250px; 
    border-radius: 5px; 
    background: white; 
    padding: 5px; 
    margin: 5px; 
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); 
} 

.photo .heart { 
    height: 16px; 
    position: absolute; 
    left: 13px; 
    bottom: 16px; 
    padding: 0 5px 0 22px; 
    font-size: 12px; 
    font-weight: bold; 
    line-height: 16px; 
    border-radius: 2px; 
    border: 1px solid #ddd; 
    background: white url('http://grammy.eduvoyage.com/images/fav.png') no-repeat 2px 0; 
} 

.paginate { 
    display: block; 
    clear: both; 
    margin: 10px; 
    text-align: center; 
    margin: 0 auto; 
    padding: 20px 0; 
    height: 100px; 
} 

.location { 
    position: relative; 
    top: -48px; 
    left: 7px; 
    border-style: solid; 
    border-width: 1px; 
    border-radius: 3px; 
    background-color: white; 
} 

HTML

 <div id='photos-wrap'> 
     </div> 

     <div class='paginate'> 
     <a class='btn' style='display:none;' data-max-tag-id='' href='#'>View More...</a> 
     </div> 
    </div> 
    </div> 
</div> 

<script type="text/template" id="photo-template"> 
    <div class='photo'> 
    <a href='<%= url %>' target='_blank'> 
     <img class='main' src='<%= photo %>' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);'/> 
    </a> 
    <img class='avatar' width='40' height='40' src='<%= avatar %>' /> 
    <span class='heart'><strong><%= count %></strong></span> 
    <span class='location'><%= longitude %> <%= latitude %></span> 
    </div> 
</script> 

Javascript

// Instantiate an empty object. 
var Instagram = {}; 

// Small object for holding important configuration data. 
Instagram.Config = { 
    clientID: '4895197dfce340cb9004101ce6ae9215', 
    apiHost: 'https://api.instagram.com' 
}; 


// ************************ 
// ** Main Application Code 
// ************************ 
(function(){ 
    var photoTemplate, resource; 

    function init(){ 
    bindEventHandlers(); 
    photoTemplate = _.template($('#photo-template').html()); 
    } 

    function toTemplate(photo){ 
    photo = { 
     count: photo.likes.count, 
     avatar: photo.user.profile_picture, 
     photo: photo.images.low_resolution.url, 
     url: photo.link, 
     longitude: photo.location && photo.location.longitude, 
     latitude: photo.location && photo.location.latitude 
    }; 

    return photoTemplate(photo); 
    } 

    function toScreen(photos){ 
    var photos_html = ''; 

    $('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id) 
        .fadeIn(); 

    $.each(photos.data, function(index, photo){ 
     photos_html += toTemplate(photo); 
    }); 

    $('div#photos-wrap').append(photos_html); 
    } 

    function generateResource(tag){ 
    var config = Instagram.Config, url; 

    if(typeof tag === 'undefined'){ 
     throw new Error("Resource requires a tag. Try searching for cats."); 
    } else { 
     // Make sure tag is a string, trim any trailing/leading whitespace and take only the first 
     // word, if there are multiple. 
     tag = String(tag).trim().split(" ")[0]; 
    } 

    url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&client_id=" + config.clientID; 

    return function(max_id){ 
     var next_page; 
     if(typeof max_id === 'string' && max_id.trim() !== '') { 
     next_page = url + "&max_id=" + max_id; 
     } 
     return next_page || url; 
    }; 
    } 

    function paginate(max_id){  
    $.getJSON(generateUrl(tag), toScreen); 
    } 

    function search(tag){ 
    resource = generateResource(tag); 
    $('.paginate a').hide(); 
    $('#photos-wrap *').remove(); 
    fetchPhotos(); 
    } 

    function fetchPhotos(max_id){ 
    $.getJSON(resource(max_id), toScreen); 
    } 

    function bindEventHandlers(){ 
    $('body').on('click', '.paginate a.btn', function(){ 
     var tagID = $(this).attr('data-max-tag-id'); 
     fetchPhotos(tagID); 
     return false; 
    }); 

    // Bind an event handler to the `submit` event on the form 
    $('form').on('submit', function(e){ 

     // Stop the form from fulfilling its destinty. 
     e.preventDefault(); 

     // Extract the value of the search input text field. 
     var tag = $('input.search-tag').val().trim(); 

     // Invoke `search`, passing `tag` (unless tag is an empty string). 
     if(tag) { 
     search(tag); 
     }; 

    }); 

    } 

    function showPhoto(p){ 
    $(p).fadeIn(); 
    } 

    // Public API 
    Instagram.App = { 
    search: search, 
    showPhoto: showPhoto, 
    init: init 
    }; 
}()); 

$(function(){ 
    Instagram.App.init(); 

    // Start with a search on cats; we all love cats. 
    Instagram.App.search('cats'); 
}); 

На jsfiddle

+0

Я видел способ в PHP для фильтрации результатов, чтобы показывать только изображения с элементами местоположения; это можно сделать и в JS? В конечном счете, я хочу получить информацию о местоположении и отобразить ее на картах Google, чтобы вы могли видеть координаты на карте. – user2371067

+0

Я бы предположил, что вы можете фильтровать клиентскую сторону с помощью Javascript, я не понимаю, почему нет. – Xotic750