我目前正在使用Google Maps API和Google商家信息库创建网站。当我第一次没有谷歌地方功能,地图工作正常。但是,当我添加Google地方信息的功能时,该部分无效。代码在这里:
function initialize ()
{
var start = new google.maps.LatLng(54.00, -3.00);
var service;
var mapOptions = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: start,
zoom: 4
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var geocoder = new google.maps.Geocoder();
var address = $("#ilocation").val();
var coords;
geocoder.geocode({'address': address},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
var bounds = new google.maps.LatLngBounds();
document.write(bounds.extend(results[0].geometry.location));
map.fitBounds(bounds);
new google.maps.Marker(
{
position:results[0].geometry.location,
map: map
}
);
}
coords = results[0].geometry.location;
}
);
alert(coords);
var request = {
location: coords,
radius: '500',
types: ['store']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
};
我没有很多javascript的经验,所以它可能是一个非常简单的东西,我很想念。感谢。
答案 0 :(得分:0)
Geocoder会从文本字符串中获取位置,现在您必须将此位置信息传递给您的位置功能。我已将google地方代码包装在一个函数中,并从地理编码器中调用它。
..................
var address = '12 Crest View Ct';
geocoder.geocode({'address': address},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK){
loc = results[0].geometry.location;
var bounds = new google.maps.LatLngBounds();
document.write(bounds.extend(results[0].geometry.location));
map.fitBounds(bounds);
new google.maps.Marker({
position:results[0].geometry.location,
map: map
});
place(loc); //here is the function call
}
}
);
现在地方功能如下:
function place(loc){
var request = {
location: new google.maps.LatLng(loc.pb, loc.qb),
radius: '500',
types: ['store'],
//keyword: address
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
console.log(place)
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
}
我创建了一个有效的演示here 转到页面右上角,然后单击Edit JS BIn以查看源代码。希望这会有所帮助...