地理位置:添加用户位置Ruby on Rails

时间:2018-01-15 16:15:50

标签: javascript ruby-on-rails google-maps geolocation google-geocoder

我的地图上有用户位置,周围有商店(商店模型)。 我使用了Google Documentation,但我迷失了...... 实际上,我有我的地图与商店,地图移动到用户位置,但没有显示infoWindow"找到位置"。

这是我的map.js:

    import GMaps from 'gmaps/gmaps.js';
import { autocomplete } from '../components/autocomplete';

const mapElement = document.getElementById('map');
if (mapElement) { // don't try to build a map if there's no div#map to inject in
  const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
  const markers = JSON.parse(mapElement.dataset.markers);
  map.addMarkers(markers);

  if (markers.length === 0) {
    map.setZoom(2);
  } else if (markers.length === 1) {
    map.setCenter(markers[0].lat, markers[0].lng);
    map.setZoom(14);
  } else {
    map.fitLatLngBounds(markers);
  }


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      var infoWindow = new google.maps.InfoWindow({map: map});

      infoWindow.setPosition(pos);
      infoWindow.setContent('Location found.');
      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
  }


  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }

}

控制器:

class PagesController < ApplicationController
  skip_before_action :authenticate_user!

  def home
    @store_all = Store.all
    @stores = Store.where.not(latitude: nil, longitude: nil)
    @markers = @stores.map do |store|
      {
        lat: store.latitude,
        lng: store.longitude,
        infoWindow: { content: '<a href="/stores/' + store.id.to_s + '">' + store.name + '</a><br/>' +
                               store.category +
                               '<br>' +
                               store.address
        }
      }
    end
  end
end

观点:

<div class="wrapper-map text-center">
    <div class="container">
      <div class="row">
        <div class="col-xs-12">
          <div
            id="map"
            style="width: 100%;
            height: 600px;"
            data-markers="<%= @markers.to_json %>"
          ></div>
        </div>
      </div>
    </div>
  </div>

感谢您的帮助,我尝试了很多教程,但我输了。 :)

0 个答案:

没有答案