HTML-шаблон обновлен с данными API прогноза

0

Следующие скрипты работают нормально, однако мне нужно обновить содержимое "contentString" данными, поступающими из API прогноза, в зависимости от того, в каком городе я искал:

var geocoder,
    map,
    button = $('button'),
    url = "https://api.forecast.io/forecast/APIKEY/";

var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
    '<div id="bodyContent">'+
    '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
    'sandstone rock formation in the southern part of the '+
    'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) '+
    'south west of the nearest large town, Alice Springs; 450&#160;km '+
    '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major '+
    'features of the Uluru - Kata Tjuta National Park. Uluru is '+
    'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
    'Aboriginal people of the area. It has many springs, waterholes, '+
    'rock caves and ancient paintings. Uluru is listed as a World '+
    'Heritage Site.</p>'+
    '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
    'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
    '(last visited June 22, 2009).</p>'+
    '</div>'+
    '</div>';

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);


}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });

      var infowindow = new google.maps.InfoWindow({
          content: contentString
      });

      var marker = new google.maps.Marker({
          position: marker.position,
          map: map,
          title: 'Uluru (Ayers Rock)'
      });
      google.maps.event.addListener(marker, 'click', function() {
        $.ajax({
          url: url+marker.position.ob+","+marker.position.pb+"",
          dataType: "jsonp",
          success: function (data) {
            console.log(data);
            infowindow.open(map,marker);
          }
        });
      });
    } 
    else {
      alert('Geocode was not successful for the following reason: ' + status);
    }

  });
}

// On page-ready
$(document).ready(function(){

  initialize();
  button.click(function(){
    codeAddress();
  });

});

API прогноза возвращает много подробной информации, которую я хотел бы отображать с помощью CSS3. Однако мне нужно убедиться, что данные, относящиеся к каждому городу, должны отображаться после появления наложений. На данный момент это только статический текст.

Теги:
google-maps

1 ответ

0

Почему вы не добавляете title когда добавляете свою позицию? :

  map.setCenter(results[0].geometry.location);
  var marker = new google.maps.Marker({
      map: map,
      position: results[0].geometry.location,
      title: results[0].formatted_address// or anything you want here 
  });

Im принимая во внимание, google maps api result выглядит примерно так:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "695564",
               "short_name" : "695564",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "Thiruvananthapuram",
               "short_name" : "TVM",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Kerala",
               "short_name" : "KL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Kerala 695564, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 8.5894172,
                  "lng" : 77.0210912
               },
               "southwest" : {
                  "lat" : 8.5616185,
                  "lng" : 76.96664299999999
               }
            },
            "location" : {
               "lat" : 8.5753702,
               "lng" : 76.99310740000001
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 8.5894172,
                  "lng" : 77.0210912
               },
               "southwest" : {
                  "lat" : 8.5616185,
                  "lng" : 76.96664299999999
               }
            }
         },
         "types" : [ "postal_code" ]
      }
   ],
   "status" : "OK"
}
  • 0
    Мне нужно использовать данные API из прогноза, а не карты Google
  • 1
    Хорошо, тогда просто переберите свой результат API, а затем добавьте маркер.
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню