在javascript中将lat long转换为Address

时间:2012-07-09 02:52:49

标签: ruby google-maps geocode google-geocoding-api

我正在尝试将markerWindow中的显示从lat long更改为地址。我无法理解Google API如何执行此操作。我愿意使用Google API或地理编码器gem,无论哪种方式更好。我只是不确定如何将它们中的任何一个包含在我的代码中。

    var map;
  function initialize() {

    //initializing map view
    var myOptions = {
      zoom: 13,
      center: new google.maps.LatLng(42.32657009662249, -71.06678009033203),
      disableDefaultUI: true,
      panControl: true,
      zoomControl: true,

      scaleControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP, 
      panControl: true,
      panControlOptions: {
        position: google.maps.ControlPosition.TOP_RIGHT
      },
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.TOP_RIGHT
      }
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
        myOptions);

    //BIKE STUFF
    var bikeLayer = new google.maps.BicyclingLayer();
    bikeLayer.setMap(map);

    <% @Reports.each do |x|%>
      addMarker(<%= x.latitude %>, <%=x.longitude%>);
    <% end %>
  }

  function addMarker(lat, long){
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(lat, long),
          map: map,
          title: 'REPORT'
        });
        //DROP PIN
        marker.setAnimation(google.maps.Animation.DROP);
        marker.setTitle('DROP');
        //DROP MARKER INFOWINDOW
        var latlng = new google.maps.LatLng(lat, long);
        google.maps.event.addListener(marker, 'click', function(){
          infowindow.open(map, this);
          marker = this
        });
        var infowindow = new google.maps.InfoWindow({
          content:"Lat: " + lat + ", Long: " + long
        });
        //CLOSING MARKER INFOWINDOW
        google.maps.event.addListener(infowindow,'closeclick',function(){
          infowindow.close(map, this); //removes the marker
        });
    }    
  console.log("message")
  google.maps.event.addDomListener(window, 'load', initialize);

相反,它在InfoWindow中显示内容,我希望它显示地址。

1 个答案:

答案 0 :(得分:0)

从现有代码开始,显示标记地址的一种方法是将其存储在数据库中(或者您要查询获取纬度和经度的任何内容),然后将其传递给“addMarker”调用(更改addMarker函数以接受包含地址的第三个参数后。

未经测试:

function addMarker(lat, long, address){
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, long),
      map: map,
      title: 'REPORT'
    });
    //DROP PIN
    marker.setAnimation(google.maps.Animation.DROP);
    marker.setTitle('DROP');
    //DROP MARKER INFOWINDOW
    var latlng = new google.maps.LatLng(lat, long);
    google.maps.event.addListener(marker, 'click', function(){
      infowindow.open(map, this);
      marker = this
    });
    var infowindow = new google.maps.InfoWindow({
      content:address
    });

如果您还没有存储地址,可以使用Google的地理编码服务作为反向地理编码器将lat / lng转换为地址。

编辑: 您可以从讨论地理编码策略的文档中查看此"article",地理编码器和反向地理编码器服务类似,并且适用相同的配额和速率限制。