我有一个 Ionic/PhoneGap 应用程序,它使用 Google map google.maps.DistanceMatrixService()
服务计算两个位置之间的距离。
当我在网络浏览器中ionic服务
应用程序时,这工作正常,但当我将其安装到我的测试设备(Samsung Galaxy S4 - 5.0)上时,它不起作用,并且不起作用我的意思是我没有得到任何回调(来自延迟对象或 try catch 语句),因此无法调试。
我的代码
工厂包装类:
.factory('GmapsWrapper', function ($q) {
function _GetLatLngObject(lat, lng) {
console.log('Gmaps Wrapper - getting new lat lng object...');
try {
return new google.maps.LatLng(lat, lng);
} catch (err) {
console.log('*google.maps.LatLng()* error: ' + err.message);
return null;
}
}
function _GetJourneyDistance(startLat, startLng, endLat, endLng) {
console.log('Gmaps Wrapper - calculating journey distance...');
var d = $q.defer();
try {
var origin = _GetLatLngObject(startLat, startLng);
var destination = _GetLatLngObject(endLat, endLng);
console.log('origin: ' + angular.toJson(origin));
console.log('destination: ' + angular.toJson(destination));
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
console.log('*service.getDistanceMatrix* callback: response = ' + angular.toJson(response) + ', status = ' + status);
d.resolve(response, status);
});
} catch (err) {
console.log('*google maps service.getDistanceMatrix()* error: ' + err.message);
d.reject(err);
}
return d.promise;
}
return {
GetJourneyDistance: _GetJourneyDistance,
GetLatLngObject: _GetLatLngObject
}
});
Controller 函数调用 GetJourneyDistance
方法:
function Calc() {
GmapsWrapper.GetJourneyDistance(52.8425701, -1.3493778, 52.8460761, -1.3363366).then(function (data, status) {
PopupWrapper.ShowAlert('Calculte Distance', 'Success.');
if (data.rows && data.rows.length > 0) {
var distance = data.rows[0].elements[0].distance;
PopupWrapper.ShowAlert('Distance', 'Km = ' + EbiLibrary.ConvertMetersToKm(distance.value) + '<br />Miles = '
+ EbiLibrary.ConvertMetersToMiles(distance.value));
}
}, function (err) {
PopupWrapper.ShowAlert('Calculate Distance', 'Error: ' + angular.toJson(err));
});
}
index.html脚本引用:
<script src="https://maps.googleapis.com/maps/api/js?key=[MY KEY]&sensor=true"></script>
config.xml 白名单:
<access origin="https://maps.googleapis.com/maps/api/*" />
其他信息
我知道 Google map 脚本已正确添加到我的 index.html
文件中,因为当我 console.log
时,它将原点和目的地变量显示为 lat lng使用 new google.maps.LatLng(lat, lng)
方法创建的对象。
最佳答案
感谢@Joerg 为我指明了正确的方向。我使用开发人员工具检查使用 ionic serve
时发出了哪些请求并注意到提出了三个请求:
- 其中两个以 https://maps.googleapis.com/maps 开头
- 另一个是 https://maps.googleapis.com/maps-api-v3 (这不符合我的白名单规则)
所以我已将白名单更改为 <access origin="https://maps.googleapis.com/*" />
目前看来已经解决了。
关于javascript - Google Maps JavaScript API 可在浏览器中使用,但无法在设备上的 Cordova 应用程序中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34266872/