gpt4 book ai didi

javascript - 通过 Google 地方信息显示当前位置

转载 作者:行者123 更新时间:2023-12-03 09:33:35 25 4
gpt4 key购买 nike

我使用下面的示例代码来展示 Google 地方信息的自动完成搜索。目前它默认当前位置为澳大利亚悉尼。

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

我目前正在收集用户位置的纬度和经度:

架构.rb

  create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "latitude"
t.float "longitude"
end

如何修改我假设的这部分(不确定为什么那里有两组坐标)

 var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);

默认为我用户的当前位置?

最佳答案

我在 Rails 中构建了一个类似的解决方案。基本上,我向 Rails Controller 中的方法发出 ajax 请求,并将用户记录作为 JSON 返回,该记录可用于设置我们的 map 。我已经调整了代码以满足您的具体需求。

我们首先在 asset pipeline 下设置一个单独的 js 文件:

将以下内容放在/app/assets/javascripts/gmap.js 下

  var worldMap = {
init: function(){
// fetch our user record for lat/long
$.ajax({
url: '/user/location',
dataType: 'json',
success: function( data ){
worldMap.lat = data.latitude;
worldMap.lng = data.longitude;
worldMap.setupMap();
}
});
},
setupMap: function(){
// we now have user location loaded so build map
worldMap.map = new google.maps.Map( document.getElementById( "map" ), {
zoom: 3,
center: {
lat: worldMap.lat,
lng: worldMap.lng
}
});

// now lets add autocomplete search
var searchbox = (document.getElementById('search-controls'));
var input = document.getElementById('pac-input');
worldMap.map.controls[ google.maps.ControlPosition.LEFT_TOP ].push( searchbox );

var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', worldMap.map);

google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) { return; }

// center map on chosen location
if (place.geometry.viewport) {
worldMap.map.fitBounds(place.geometry.viewport);
} else {
worldMap.map.setCenter(place.geometry.location);
worldMap.map.setZoom(17);
}
});
}
}

然后,一旦 DOM 加载,我们就可以调用新的 map 设置代码,并将其添加到/app/assets/javascripts/application.js 中:

window.onload = function(){
worldMap.init();
}

现在我们可以设置路由,将此行添加到/config/routes.rb:

get 'user/location', :controller => 'users', :action => 'user_location', :as => 'user_latlng'

然后最后将该方法添加到我们的用户 Controller /app/controllers/users_controller.rb:

def user_location
@user = User.select(:latitude, :longitude).where(id: current_user.id).limit(1)
render json: @user.first
end

在您看来,您将需要我们的 JS 正在寻找的搜索框和 map div:

<div id="search-controls" class="controls">
<input type="text" id="pac-input" placeholder="Search" />
</div>

<div id="map"></div>

关于javascript - 通过 Google 地方信息显示当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31412357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com