我从Json抓取数据并在queryLat / queryLng中包含数组,然后创建了另一个函数initMap还将其绑定到Google脚本。但是我很难及时将queryLat和queryLng传递到initMap中。弹出“ queryLat未定义”。我如何将它们传递给initMap。
var queryLat = [];
var queryLng = [];
@foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
@endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
答案 0 :(得分:2)
对于多个标记,如果要全局定义数组,则必须将lat和long值压入数组,还需要更新marker变量以显示不同的标记。希望它能帮助您获得多个标记。
var queryLat = []; var queryLng = [];
@foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
@endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
答案 1 :(得分:1)
您应该在脚本开始的位置全局定义变量queryLat和queryLng。
<script type="text/javascript">
var queryLat;
var queryLng;
@foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
@endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
答案 2 :(得分:0)
问题出在此代码中:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
您已经用撇号将字符串括起来,但是字符串中也包含了撇号。
改为使用此:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"