Google maps 使用边界选项限制Google自动完成结果

Google maps 使用边界选项限制Google自动完成结果,google-maps,google-maps-api-3,autocomplete,google-places-api,Google Maps,Google Maps Api 3,Autocomplete,Google Places Api,我正在尝试使用Google Places Autocomplete,并将结果限制在加拿大的一个特定城市,即多伦多。我知道使用componentRestrictions选项将允许我使用componentRestrictions:{country:'CA'}将结果限制在加拿大。为了进一步将结果限制在多伦多,我知道我必须将bounds属性添加到options对象中。LatLngBounds需要西南角和东北角,也被称为左下角和右上角 我在巴基斯坦的海得拉巴市发现了这个示例代码,它实现了这个策略,并且非常

我正在尝试使用Google Places Autocomplete,并将结果限制在加拿大的一个特定城市,即多伦多。我知道使用
componentRestrictions
选项将允许我使用
componentRestrictions:{country:'CA'}
将结果限制在加拿大。为了进一步将结果限制在多伦多,我知道我必须将
bounds
属性添加到
options
对象中。
LatLngBounds
需要西南角和东北角,也被称为左下角和右上角

我在巴基斯坦的海得拉巴市发现了这个示例代码,它实现了这个策略,并且非常有效:

var input = document.getElementById('searchTextField');
var southWest = new google.maps.LatLng( 25.341233, 68.289986 );
var northEast = new google.maps.LatLng( 25.450715, 68.428345 );
var HyderabadBounds = new google.maps.LatLngBounds( southWest, northEast );

var options = {
    bounds: HyderabadBounds,
    types:  ['address'],
    componentRestrictions: { country: 'PK' }
};

var autocomplete = new google.maps.places.Autocomplete( input, options);
当我试图修改代码以适用于加拿大的某个地区时,由于某种原因,它不起作用。这是我修改过的代码:

var input = document.getElementById('searchTextField');
var southWest = new google.maps.LatLng( 43.941160, -78.895187 );
var northEast = new google.maps.LatLng( 42.946172, -81.296577 );
var TorontoBounds = new google.maps.LatLngBounds( southWest, northEast );

var options = {
    bounds: TorontoBounds,
    types:  ['address'],
    componentRestrictions: { country: 'CA' }
};

var autocomplete = new google.maps.places.Autocomplete( input, options);
我修改的代码唯一不同的地方是国家名称
CA
和我认为正确的车床坐标。我仔细检查了我的坐标,西南坐标指的是多伦多西南的一个位置,东北坐标指的是多伦多东北的一个位置,所以我希望这些都能起作用。虽然我的结果仅限于加拿大,但它们不在LatLng坐标指定的范围内


有人能看出我可能做错了什么吗

您的
东北
西南
点命名不正确。更改他们的姓名:

var northEast = new google.maps.LatLng(43.941160, -78.895187);
var southWest = new google.maps.LatLng(42.946172, -81.296577);  

如果我将它们设置为:

var northEast = new google.maps.LatLng(43.941160, -78.895187);
var southWest = new google.maps.LatLng(42.946172, -81.296577);
边界对象是正确的

代码片段:

//此示例需要Places库。包括图书馆=地方
//第一次加载API时的参数。例如:
// 
函数initMap(){
var map=new google.maps.map(document.getElementById('map'){
中心:{
lat:-33.8688,
液化天然气:151.2195
},
缩放:13
});
var input=document.getElementById('searchTextField');
var northEast=new google.maps.LatLng(43.941160,-78.895187);
var西南=新google.maps.LatLng(42.946172,-81.296577);
var SWmark=new google.maps.Marker({
地图:地图,
位置:西南,,
标题:西南。旅游价值(6),
标签:“SW”
});
var NEmark=new google.maps.Marker({
地图:地图,
位置:东北,
标题:东北。旅游价值(6),
标签:“NE”
});
var torontobunds=new google.maps.LatLngBounds(西南、东北);
var rectangle=new google.maps.rectangle({
地图:地图,
边界:TorontoBounds
});
映射fitBounds(TorontoBounds);
变量选项={
边界:TorontoBounds,
类型:[“地址”],
组件限制:{
国家:'CA'
}
};
var autocomplete=new google.maps.places.autocomplete(输入,选项);
}
/*始终明确设置贴图高度以定义div的大小
*包含映射的元素*/
#地图{
身高:80%;
}
/*可选:使示例页面填充窗口*/
html,
身体{
身高:100%;
保证金:0;
填充:0;
}



在此处查看我的答案,希望能有所帮助: