Добавить информационное окно при нажатии на маркер с помощью geocomplete в Rails 3.2

#ruby-on-rails #ruby-on-rails-3 #google-maps #geocode #rails-geocoder

#ruby-on-rails #ruby-on-rails-3 #google-карты #геокодирование #rails-геокодер

Вопрос:

я пытался реализовать infowindow на своей карте Google, которая отлично работает, используя geocomplete.js для поиска / получения подробной информации об улице, а также для получения lang / lat. Теперь мне нужно информационное окно на маркере, чтобы, когда пользователь нажимает на маркер, я мог показать немного больше информации, но я не могу заставить его работать, поскольку я не могу получить какую-либо ошибку, чтобы я мог ее отладить и устранить. я знаю, что чего-то не хватает, но я думаю, что мой код ошибочен.просто, и я должен получить infowindow.Вот мой код _view.html.erb , который отображается в модальном режиме bootstrap 3.

 <script src="http://maps.googleapis.com/maps/api/js?sensor=falseamp;amp;libraries=places"></script>
  <script src="assets/jquery.geocomplete.js"></script>
<p class="text-center text-success">Add a location</p>
<hr>
 <div class="container">
 <%= form_for(@place,:html=>{:multipart => true,:remote=>true,:class=>"form-horizontal",:role=>"form"}) do |f |%>

      <%= f.text_field :address,:class=>"form-control" %>
      <p class="text-info" style="font-size:10px !important;">if you cannot find the location,Drag the marker on the map. </p>

          <div id="logs" data-lat="<%=  current_user.latitude%>" data-long="<%=  current_user.longitude%>">
              <%= current_user.address %> 
          </div>    


      <div id="mapnew" style="width:500px;height:500px"></div>

  <%end%>

  </div>   


<script type="text/javascript">


var lat=$('#logs').data("lat");
var long=$('#logs').data("long");


  var myLatlng = new google.maps.LatLng(lat,long);
var options = {
  map: "#mapnew",
  location: myLatlng,
  mapOptions: {
    streetViewControl: false,
    center: myLatlng,
    mapTypeId : google.maps.MapTypeId.ROADMAP
  },
  markerOptions: {
    draggable: true
  }
};


function initialize(){
$("#place_address").geocomplete(options).bind("geocode:result", function(event, result){
  $('#logs').html('<b>' result.formatted_address '</b>');
  var map = $("#place_address").geocomplete("map");
  map.setZoom(15);
  map.setCenter(result.geometry.location);
  //get the marker
  /////////////////////////////here i get the marker to set the infowindow but doesnt works
  ////////////////////This code is not working -START
  var marker = $("#place_address").geocomplete("marker");
  marker.setMap(map);
  var infowindow = new google.maps.InfoWindow({
  content:"Hello World!"
  });

  google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map,marker);
  });
 ///////////////////////This code is not working-ENDS  
});//method ends

$("#place_address").bind("geocode:dragged", function(event, latLng){
  console.log('Dragged Lat: ' latLng.lat());
  console.log('Dragged Lng: ' latLng.lng());
//set to true to save the coordinated directly in db without using geocoder
  var map = $("#place_address").geocomplete("map");
    map.panTo(latLng);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': latLng }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        var road = results[0].address_components[1].long_name;
        var town = results[0].address_components[2].long_name;
        var county = results[0].address_components[3].long_name;
        var country = results[0].address_components[4].long_name;
        $('#logs').html('<b>' road ' ' town ' ' county ' ' country '</b>');

      }
    }
  });
});//method ends

}//initialize method ends

$(document).ready(function(){
  $('#mapnew').html("<p class='text-center text-alert'><b><i>Loading map...</i><i class='fa fa-spinner fa-spin fa-2x'></i></b></p>");
//load the map after 2 seconds to avoid blurring
setTimeout('initialize()', 3000);
})//document ready ends
</script>
  

Ответ №1:

Ваш скрипт, как он есть, работает для меня, но, возможно, вы не получите желаемого результата.

Маркер, который изначально нарисован на карте, создается на основе options.location

Вы уже указали LatLng for location , поэтому геокодировать нечего, и обработчик geocode:result -не будет запущен при создании этого маркера (поэтому infowindow не будет добавлено)

Возможное решение: запустить geocode:result событие -event и передать уже доступные данные:

 $("#place_address")
  .geocomplete(options)
    .bind("geocode:result", function(event, result){ 
      $('#logs').html('<b>' result.formatted_address '</b>');
      var map = $("#place_address").geocomplete("map"),
///////////////////////This code should work now as expected-STARTS 
          marker = $("#place_address").geocomplete("marker");

          //there is only a single marker, use only a single infowindow
          if(!marker.get('infowindow')){
            marker.set('infowindow',new google.maps.InfoWindow());
            google.maps.event.addListener(marker, 'click', function() {
              this.get('infowindow').open(map,this);
            });
          }
      marker.get('infowindow').close();    
      map.setZoom(15);
      map.setCenter(result.geometry.location);
      marker.setMap(map);
      marker.get('infowindow').setContent(result.formatted_address)


 ///////////////////////This code should work now as expected-ENDS  
})
//method ends
//trigger the event
.trigger('geocode:result',
         {geometry:{location:myLatlng},
          formatted_address:$('#logs').text()});
  

Комментарии:

1. спасибо @Dr.Molle, НО все же, когда я нажимаю на свой маркер … я ничего не вижу,,, ПЛЮС нет ошибки в firebug console….so мы что-то упускаем???

2. Я ничего не пропустил и вижу информационное окно: jsfiddle.net/doktormolle/8FH9u