2015-11-08 3 views
0

Я стараюсь следовать учебнику this, чтобы сделать вложенную карту Google, которая отображает все мои геотегированные фотографии Flickr в качестве маркеров, показывающих, где они были сделаны. Я не уверен, что что-то изменилось либо с помощью GMaps, либо с API Flickr, поскольку учебник был написан два года назад, но маркеры не отображаются в example given in the tutorial, а также когда я пытаюсь использовать его с фотографиями Flickr. Я не очень хорошо разбираюсь в кодировании, поэтому я не могу понять, почему они не появятся, и я часами просматривал веб-часы без везения. Кажется, нет никаких альтернативных способов получить такую ​​карту, поэтому, если бы кто-нибудь мог предложить любую помощь, я был бы очень благодарен!Создайте Google Map с Geotagged Flickr Photos

<!DOCTYPE html> 
<html> 
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 

<title>Google and Flickr API mashup</title> 

<style type="text/css"> 
     html { height: 100% } 
     body { height: 100%; margin: 0; padding: 0 } 
     #map_canvas { height: 100% } 
</style> 

<!--Linking to the jQuery library.--> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> 

<!--Linking to the Google Maps API--> 
<script type="text/javascript" 
     src="https://maps.googleapis.com/maps/api/js?key=AIzaSyASqSk7-yzQzHkrLVKhjQNBup2Wd-XQkQ0&sensor=true"> 
</script> 

<script type="text/javascript"> 

var lat = 0; 
var long = 0; 

$(document).ready(function(){ 

//Connects to the Flickr API and reads the results of the query into a JSON array. This query uses the 'flickr.photos.search' method to access all the photos in a particular person's user 

account. It also uses arguments to read in the latitude and longitude of each picture. It passes the resultant JSON array to the 'displayImages3' function below. 
$.getJSON("https://api.flickr.com/services/rest/? 

method=flickr.photos.search&api_key=14fca78b18f8e8f4d22216494ea29abf&user_id=136688117%40N05&has_geo=1&extras=geo&format=json&nojsoncallback=?", displayImages3); 

function displayImages3(data){ 

        //Loop through the results in the JSON array. The 'data.photos.photo' bit is what you are trying to 'get at'. i.e. this loop looks at each photo in turn. 
        $.each(data.photos.photo, function(i,item){ 

        //Read in the lat and long of each photo and stores it in a variable. 
        lat = item.latitude; 
        long = item.longitude; 

        //Get the url for the image. 
        var photoURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';  
        htmlString = '<img src="' + photoURL + '">';      
        var contentString = '<div id="content">' + htmlString + '</div>'; 

        //Create a new info window using the Google Maps API 
        var infowindow = new google.maps.InfoWindow({ 
         //Adds the content, which includes the html to display the image from Flickr, to the info window. 
         content: contentString 
        }); 

        //Create a new marker position using the Google Maps API. 
        var myLatlngMarker = new google.maps.LatLng(lat,long); 

        //Create a new marker using the Google Maps API, and assigns the marker to the map created below. 
        var marker = new google.maps.Marker({ 
        position: myLatlngMarker, 
        map: myMap, 
        title:"Photo" 
        }); 

        //Uses the Google Maps API to add an event listener that triggers the info window to open if a marker is clicked. 
        google.maps.event.addListener(marker, 'click', function() { 
        infowindow.open(myMap,marker); 
        });     
     });     
} 

}); 

</script> 

</head> 
<body> 

<p>Google maps and Flickr API mashup</p> 
<p>&nbsp;</p> 

<div id="map_canvas"> 
<script> 
//Using the Google Maps API to create the map. 
var myLatlngCenter = new google.maps.LatLng(41.79179, -119.36646); 
var mapOptions = { 
      center: myLatlngCenter, 
      zoom: 5, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
}; 
var myMap = new google.maps.Map(document.getElementById("map_canvas"),mapOptions); 
</script> 
</div> 

</body>   
</html> 
+0

Посмотрите на это: http://gis.yohman.com/up206b/tutorials/api-access-flickr/ –

+0

[Этот пример] (http://tutsplus.github.io/Google-Maps-and -Flickr-API/part2/tutorial3_part2_google_maps_flickr_mashup.html) имеет ошибку javascript 'Uncaught SyntaxError: Неожиданный токен <' – geocodezip

+0

@eugensunic Я также прочитал этот учебник, очень полезный и информативный. Однако их пример имеет ту же самую проблему; фотографии/маркеры не отображаются на карте. Все, что я вижу, это пустая карта, сосредоточенная на Санта-Монике. Работает ли это для вас? – merzperson

ответ

0

Я просто НАКОНЕЦ получил эту работу! Такое простое решение. Я заметил, что Flickr обновил свою политику API, чтобы разрешить только https, а не http. Я изменил URL-адрес API-интерфейса на https вручную, но я пропустил photoURL. Добавление простой буквы 'после' http 'в photoURL привело к созданию рабочей встраиваемой фотокарты, показывающей мои геотегированные фотографии Flickr. Надеюсь, это поможет кому-то другому.

+0

См. Мой ответ, в настоящее время требуются дополнительные изменения. – robermann

0

Спустя два года после ответа orignal и некоторых обновлений политик Flickr и jquery под полным рабочим примером.

<!DOCTYPE html> 
<html> 
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 

<title>Google and Flickr API mashup</title> 

<style type="text/css"> 
     html { height: 100% } 
     body { height: 100%; margin: 0; padding: 0 } 
     #map_canvas { height: 100% } 
</style> 

<!--Linking to the jQuery library.--> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script> 

<!--Linking to the Google Maps API--> 
<script type="text/javascript" 
     src="https://maps.googleapis.com/maps/api/js?key=AIzaSyASqSk7-yzQzHkrLVKhjQNBup2Wd-XQkQ0"> 
</script> 

<script type="text/javascript"> 

//See here: https://stackoverflow.com/questions/33591826/create-google-map-with-geotagged-flickr-photos 

var lat = 0; 
var long = 0; 

$(document).ready(function(){ 


//Connects to the Flickr API and reads the results of the query into a JSON array. This query uses the 'flickr.photos.search' method to access all the photos in a particular person's user account. It also uses arguments to read in the latitude and longitude of each picture. It passes the resultant JSON array to the 'displayImages3' function below. 
$.getJSON("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=14fca78b18f8e8f4d22216494ea29abf&user_id=136688117%40N05&has_geo=1&extras=geo&format=json&nojsoncallback=1", displayImages3); 

function displayImages3(data){ 

        //Loop through the results in the JSON array. The 'data.photos.photo' bit is what you are trying to 'get at'. i.e. this loop looks at each photo in turn. 
        $.each(data.photos.photo, function(i,item){ 

         //Read in the lat and long of each photo and stores it in a variable. 
         lat = item.latitude; 
         long = item.longitude; 

         //Get the url for the image. 
         var photoURL = 'https://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';  
         htmlString = '<img src="' + photoURL + '">';      
         var contentString = '<div id="content">' + htmlString + '</div>'; 

         //Create a new info window using the Google Maps API 
         var infowindow = new google.maps.InfoWindow({ 
          //Adds the content, which includes the html to display the image from Flickr, to the info window. 
          content: contentString 
         }); 

         //Create a new marker position using the Google Maps API. 
         var myLatlngMarker = new google.maps.LatLng(lat,long); 
         var myTitle = "" +item.title; 

         //Create a new marker using the Google Maps API, and assigns the marker to the map created below. 
         var marker = new google.maps.Marker({ 
         position: myLatlngMarker, 
         map: myMap, 
         title: item.title 
         }); 

         //Uses the Google Maps API to add an event listener that triggers the info window to open if a marker is clicked. 
         google.maps.event.addListener(marker, 'click', function() { 
         infowindow.open(myMap,marker); 
         });  

     });     
} 

}); 

</script> 

</head> 
<body> 

<p>Google maps and Flickr API mashup</p> 
<p>&nbsp;</p> 

<div id="map_canvas"> 
<script> 
//Using the Google Maps API to create the map. 
var myLatlngCenter = new google.maps.LatLng(41.79179, -119.36646); 
var mapOptions = { 
      center: myLatlngCenter, 
      zoom: 5, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
}; 
var myMap = new google.maps.Map(document.getElementById("map_canvas"),mapOptions); 
</script> 
</div> 

</body>   
</html> 

мне пришлось изменить:

  • Версия JQuery, так как другая версия добавлен заголовок HTTP X-Requested-With, что вызвало следующую ошибку:

XMLHttpRequest cannot load https://api.flickr.com/services/rest/method=flickr.photos.search&xxx . Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.

  • URL параметр nojsoncallback имеет значение , так как старое значение (?) вызвало ошибку:

Refused to execute script from ' https://api.flickr.com/services/rest/?method=flickr.photos.search&xxxx ' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

Я надеюсь, что это может помочь другим людям.

Смежные вопросы