Борьба с API геокодирования Карт Google - PullRequest
2 голосов
/ 30 марта 2011

В настоящее время я работаю над приложением, которое периодически (каждые 30 секунд) получает два твита в Великобритании от двух указанных футбольных команд в формате json. В файле json я могу получить доступ к местоположению каждого твита, который в настоящее время является текстовым (Манчестер, Бристоль и т. Д.).

Что мне нужно сделать, так это как-то геокодировать местоположения и использовать координаты lat, lng для размещения данных твита на нескольких (2) информационных окнах. Мне удалось использовать API геокодирования, но пока не повезло. В настоящее время я пытаюсь просто вывести co-ords в тестовый div, чтобы посмотреть, работает ли он, но это не так.

Мой общий код приведен ниже, если это поможет, любой совет или помощь по этому поводу были бы полезны! (в настоящее время я также просто выводю данные из твиттера в div-метки-заполнители)

//create urls for grabbing both teams tweets in the UK area
var url1="http://search.twitter.com/search.json?q=
%23"+team1+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var url2="http://search.twitter.com/search.json?q=
%23"+team2+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";

function team1tweets()
{
           $.getJSON(
           url1,function(results){ // get the tweets
           var res1 = results.results[0].text;
           var user1name = results.results[0].from_user;
           var user1Location = results.results[0].location;

           // get the first tweet in the response and place it inside the div
           $("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" +
user1Location + ")</p><p>");
           }
           );

           //convert location into longitude and latitude
           var convertLocUrl1 = "http://maps.googleapis.com/maps/api/geocode/
json?address=" + userLocation1 + "&sensor=false&region=uk";
           convertLocUrl1,function(locResult){
           var lat1 = locResult.results[0].geometry.location.lat();
           var lng1 = locResult.results[0].geometry.location.lng();
           $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</
p>");
           }

}

function team2tweets()
{
           $.getJSON(
           url2,function(results){ // get the tweets
           var res2 = results.results[0].text;
           var user2name = results.results[0].from_user;
           var user2Location = results.results[0].location;
           $("#last-tweet2").html(res2 + "<p>from: " + user2name + " (" +
user2Location + ")</p>"); // get the first tweet in the response and
place it inside the div
           });

//convert location into longitude and latitude
           var convertLocUrl2 = "http://maps.googleapis.com/maps/api/geocode/
json?address=" + userLocation2 + "&sensor=false&region=uk";
           convertLocUrl2,function(locResult){
           var lat2 = locResult.results[0].geometry.location.lat();
           var lng2 = locResult.results[0].geometry.location.lng();
           $("#testDiv2").html("latitude:" + lat2 + "<p>longitude:" + lng2 + "</
p>");
           }
}

team1tweets();
team2tweets();

setInterval(checkStream1,20000);
setInterval(checkStream2,20000);


function checkStream1()
{
           team1tweets();
}

function checkStream2()
{
           team2tweets();
}
});
</script>

ОБНОВЛЕНИЕ: новый код, используя Google Maps API v3

 <HTML>
<HEAD>
<TITLE>Tweet Ball</TITLE>
<LINK REL="Stylesheet" href="tweetBallStyles.css"></LINK>
<script src="https://maps-api-ssl.google.com/maps/api/js?v=3&sensor=false"
type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>

<!--GRABBING AND DISPLAYING TWEETS-->
<script type="text/javascript"> 
$(document).ready(function(){
var team1, team2; 
//get team hashtag info
team1 = '<?php echo $_GET["team1"]; ?>'; 
team2 = '<?php echo $_GET["team2"]; ?>'; 

 //create urls for grabbing both teams tweets in the UK area
var url1="http://search.twitter.com/search.json?q=%23"+team1+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var url2="http://search.twitter.com/search.json?q=%23"+team2+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var geocoder = new google.maps.Geocoder();

function team1tweets() {
$.getJSON(
url1, function(results) { // get the tweets
    var res1 = results.results[0].text;
    var user1name = results.results[0].from_user;
    var user1Location = results.results[0].location;

    // get the first tweet in the response and place it inside the div
    $("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
    //convert location into longitude and latitude
    geocoder.geocode({
        address: user1Location 
        }, function(locResult) {
            console.log(locResult);
            var lat1 = locResult[0].geometry.location.lat();
            var lng1 = locResult[0].geometry.location.lng();
            $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
    });
});
}


function team2tweets() {
$.getJSON(
url2, function(results) { // get the tweets
    var res2 = results.results[0].text;
    var user2name = results.results[0].from_user;
    var user2Location = results.results[0].location;

    // get the first tweet in the response and place it inside the div
    $("#last-tweet2").html(res2 + "<p>from: " + user2name + " (" + user2Location + ")</p><p>");
    //convert location into longitude and latitude
    geocoder.geocode({
        address: user2Location 
        }, function(locResult) {
            console.log(locResult);
            var lat2 = locResult[0].geometry.location.lat();
            var lng2 = locResult[0].geometry.location.lng();
            $("#testDiv2").html("latitude:" + lat2 + "<p>longitude:" + lng2 + "</p>");
    });
});
}


team1tweets();
team2tweets();

//setInterval(checkStream1, 10000);
//setInterval(checkStream2, 10000);

function checkStream1() {
team1tweets();
}

function checkStream2() {
team2tweets();
}})
</script>

</HEAD>


<body>
<div id="container">
<div id="header"></div><!--end of header div-->

<div id="mainContent">
<ul>
<li><a href="index.php">return to team select</li>
</ul>

<div id="testDiv"></div>
<div id="testDiv2"></div>

<div id="map_canvas"></div>

<div id="last-tweet1-container">
<div id="last-tweet1">
</div>
</div>

<div id="last-tweet2-container">
<div id="last-tweet2">
</div>
</div>



<div id="footer">
</div>
</div><!--end of mainContent div--> 
</div><!--end of container div-->
</BODY>
</HTML> 

1 Ответ

2 голосов
/ 30 марта 2011

Вот демоверсия JSFiddle: с использованием геокодирования Google Map V3 API для определения широты и долготы ваших местоположений:

Я могу без ошибок изменить ваш код на следующий.По сути, вы должны вызывать геокод Google Map в вашем первом getJSON, потому что user1Location извлекается асинхронно и, следовательно, не определяется при доступе вне вашего обратного вызова json в твиттере.AFAIK, Google Geocode VIA HTTP не допускает JSONP , поэтому получение HTTP через JavaScript VIA Ajax является нарушением междоменной политики.Еще одна альтернатива - использовать геокодирование API Google Map V3 или использовать серверную часть для получения HTTP JSON.

function team1tweets() {
    $.getJSON(
    url1, function(results) { // get the tweets
        var res1 = results.results[0].text;
        var user1name = results.results[0].from_user;
        var user1Location = results.results[0].location;

        // get the first tweet in the response and place it inside the div
        $("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
        //convert location into longitude and latitude
        var convertLocUrl1 = "http://maps.googleapis.com/maps/api/geocode/json?address=" + user1Location + "&sensor=false&region=uk";
        $.getJSON(convertLocUrl1,function(locResult) {
                var lat1 = locResult.results[0].geometry.location.lat();
                var lng1 = locResult.results[0].geometry.location.lng();
                $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
        });
    });
}

ОБНОВЛЕНИЕ:

Здесьэто Google Map API V3 способ получить LatLng мест, которые вы хотите.Примените подобный код к вашему team2tweets().Я в основном заменяю ваш $ .getJSON на google.map.Geocode:

function team1tweets() {
    $.getJSON(
    url1, function(results) { // get the tweets
        var res1 = results.results[0].text;
        var user1name = results.results[0].from_user;
        var user1Location = results.results[0].location;

        // get the first tweet in the response and place it inside the div
        $("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
        //convert location into longitude and latitude
        geocoder.geocode({
            address: user1Location 
            }, function(locResult) {
                console.log(locResult);
                var lat1 = locResult[0].geometry.location.lat();
                var lng1 = locResult[0].geometry.location.lng();
                $("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
        });
    });
}
...