Google ClientLocation API是Google提供的一个轻量级服务,用于基于IP地址获取用户的大致地理位置信息,而不需要加载完整的地图API。
// 加载Google Loader
function loadGoogleClientLocation(callback) {
window.google.loader.ClientLocation = null;
// 创建script元素加载Google Loader
const script = document.createElement('script');
script.src = 'https://www.google.com/jsapi?callback=googleLoaded';
script.onerror = function() {
console.error('Failed to load Google Loader');
callback(null);
};
document.head.appendChild(script);
// 回调函数
window.googleLoaded = function() {
google.load('clientlocation', {
callback: function() {
callback(google.loader.ClientLocation);
}
});
};
}
// 使用示例
loadGoogleClientLocation(function(location) {
if (location) {
console.log('Country: ' + location.address.country);
console.log('Region: ' + location.address.region);
console.log('City: ' + location.address.city);
console.log('Latitude: ' + location.latitude);
console.log('Longitude: ' + location.longitude);
} else {
console.log('Unable to determine location');
}
});
function getClientLocation(callback) {
const script = document.createElement('script');
script.src = 'https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY&callback=handleClientLocation';
script.onerror = function() {
callback(null);
};
document.head.appendChild(script);
window.handleClientLocation = function(response) {
callback(response);
delete window.handleClientLocation;
};
}
// 使用示例
getClientLocation(function(data) {
if (data && data.location) {
console.log('Latitude:', data.location.lat);
console.log('Longitude:', data.location.lng);
console.log('Accuracy:', data.accuracy);
} else {
console.log('Location not available');
}
});
如果Google ClientLocation API不能满足需求,可以考虑:
navigator.geolocation
(需要HTTPS)