Javascript PhoneGap+;谷歌地图API v3:在Android上根本不显示
形势 我目前正在为一位希望与谷歌地图集成的客户开发一款应用程序。他希望地图显示从用户所在地到办公室的路线 我正在使用Windows8,没有任何IDE(使用Sublime Text 2) 我已经设法让它工作a)在本地Chrome浏览器中,b)在PhoneGap/Cordova>2.0.0的Ripple Emulator中。然而,无论我何时尝试,它都无法在我的Android手机(HTC Sensation)上运行。它快把我逼疯了,我正要放下它,找到其他一些“更愚蠢”的解决方案(比如静态地图或geo:url接口) 在我尝试实际实现map之前,我运行了PhoneGap地理定位完整示例find。我注意到我的Android手机确实正确显示了我的当前位置(lat/long/timestamp等)。因此,我相信我的手机已经设置了正确的权限(位置->等) 问题 谷歌地图根本不会出现在我的Android设备上。我看到红色背景(用于调试),所以我知道高度和宽度都很好。但我看不到谷歌地图的任何迹象(没有按钮、覆盖、网格或任何东西) 代码 用于加载jQuery、Cordova和Maps API v3的HTML代码:Javascript PhoneGap+;谷歌地图API v3:在Android上根本不显示,javascript,android,google-maps,cordova,Javascript,Android,Google Maps,Cordova,形势 我目前正在为一位希望与谷歌地图集成的客户开发一款应用程序。他希望地图显示从用户所在地到办公室的路线 我正在使用Windows8,没有任何IDE(使用Sublime Text 2) 我已经设法让它工作a)在本地Chrome浏览器中,b)在PhoneGap/Cordova>2.0.0的Ripple Emulator中。然而,无论我何时尝试,它都无法在我的Android手机(HTC Sensation)上运行。它快把我逼疯了,我正要放下它,找到其他一些“更愚蠢”的解决方案(比如静态地图或geo:
<script type="text/javascript" src="js/jquery-1.10.0.min.js" ></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=true&language=da"></script>
这是我的初始化代码(放在我的头标签的底部):
在ripple emulator中,每当加载应用程序时,我都会得到“找到的用户位置”
请帮忙
[编辑]
我忘了提到我正在使用Adobe来实际构建应用程序
[编辑二]
我现在尝试使用Google API密钥,如下所示:
<script src="http://maps.google.com/maps/api/js?key=AIzaSyB1uhDdWjtNEl9K35lJtuq5Sw2BjKR8-OM&sensor=false" type="text/javascript"></script>
[编辑部4]
我现在尝试用PhoneGap地理定位和一个基本的google地图构建一个最小的示例。我用Cordova v通过Eclipse手动构建了它。2.9.0(最新版本)。
奇怪的是,PhoneGap地理定位示例本身运行良好,但当我引入谷歌地图代码时,它就停止工作了。我尝试了这个带有和不带GoogleAPI键的最小示例。没有区别
这是我使用的index.html:
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
body, html, #map-canvas {
width: 100%;
height: 400px;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
initMap();
}
// onError Callback receives a PositionError object
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var map,
userPosition,
officeLocation,
directionsDisplay,
directionsService;
function initMap() {
//directionsDisplay = new google.maps.DirectionsRenderer();
//directionsService = new google.maps.DirectionsService();
officeLocation = new google.maps.LatLng(55.689403, 12.521281);
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: officeLocation
};
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//directionsDisplay.setMap(map);
}
</script>
</head>
<body>
<p id="geolocation">Finding geolocation...</p>
<div id="map-canvas"></div>
</body>
</html>
设备属性示例
正文、html、#地图画布{
宽度:100%;
高度:400px;
保证金:0;
填充:0;
}
//等待加载设备API库
文件。添加的监听器(“deviceready”,OnDeviceraddy,false);
//设备API可用
函数ondevicerady(){
navigator.geolocation.getCurrentPosition(onSuccess,onError);
}
//成功地理定位
成功时的功能(位置){
var element=document.getElementById('geolocation');
element.innerHTML='Latitude:'+position.coords.Latitude+'
'+
'经度:'+position.coords.Longitude+'
'+
'高度:'+position.coords.altime+'
'+
'精度:'+position.coords.accurity+'
'+
'高度精度:'+position.coords.altitudeAccuracy+'
'+
'标题:'+position.coords.Heading+'
'+
'速度:'+position.coords.Speed+'
'+
'时间戳:'+position.Timestamp+'
';
initMap();
}
//OneError回调接收PositionError对象
函数onError(错误){
警报('code:'+error.code+'\n'+
'消息:'+error.message+'\n');
}
var映射,
用户位置,
办公地点,
方向显示,
指导服务;
函数initMap(){
//directionsDisplay=new google.maps.DirectionsRenderer();
//directionsService=new google.maps.directionsService();
officeLocation=new google.maps.LatLng(55.689403,12.521281);
变量myOptions={
mapTypeId:google.maps.mapTypeId.ROADMAP,
中心:办公地点
};
map=new google.maps.map(document.getElementById('map-canvas'),myOptions);
//方向显示.setMap(地图);
}
查找地理位置
[编辑部5]
我现在尝试用PhoneGap(Cordova)v构建应用程序。2.6.0、2.9.0和2.8.1-无一起作用。手机的地理定位功能正常,但谷歌地图没有显示出来。我只看到它应该在哪里的默认灰色背景 我从未直接解决过这个问题,但我开始使用,它有一个谷歌地图的示例插件(原始链接已失效,请参见下面的编辑)。这个插件非常适合我,我可以为它添加方向 下面是我最终使用的代码。无需权限或任何其他调整。请参阅代码中的注释。无论地理定位成功与否,地图都会显示,但如果它获得当前位置,它会向地图添加方向。否则它将显示一个静态点
// @author Ian Maffett
// @copyright App Framework 2012
// Modified by Rami@alphastagestudios.com - 2013
// - Added markers & directions
(function () {
var gmapsLoaded = false; //internal variable to see if the google maps API is available
//We run this on document ready. It will trigger a gmaps:available event if it's ready
// or it will include the google maps script for you
$(document).ready(function () {
if(window["google"]&&google.maps){
$(document).trigger("gmaps:available");
gmapsLoaded = true;
return true;
}
var gmaps = document.createElement("script");
gmaps.src = "http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&callback=gmapsPluginLoaded";
// Updated API url
$("head").append(gmaps);
window["gmapsPluginLoaded"] = function () {
$(document).trigger("gmaps:available");
gmapsLoaded = true;
}
});
//Local cache of the google maps objects
var mapsCache = {};
//We can invoke this in two ways
//If we pass in positions, we create the google maps object
//If we do not pass in options, it returns the object
// so we can act upon it.
$.fn.gmaps = function (opts) {
if (this.length == 0) return;
if (!opts) return mapsCache[this[0].id];
//Special resize event
if(opts=="resize"&&mapsCache[this[0].id])
{
var map = mapsCache[this[0].id];
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.setZoom(13);
// Extended resize to recenter and reset zoom
return map;
}
//loop through the items and create the new gmaps object
for (var i = 0; i < this.length; i++) {
new gmaps(this[i], opts);
}
};
//This is a local object that gets created from the above.
var gmaps = function (elem, opts) {
var createMap = function () {
var officePos = new google.maps.LatLng(55.689403, 12.521281);
if (!opts || Object.keys(opts).length == 0) {
opts = {
zoom: 13,
center: officePos,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
}
mapsCache[elem.id] = new google.maps.Map(elem, opts);
// Added marker for static location
var officeMarker = new google.maps.Marker({
position: officePos,
map: mapsCache[elem.id],
title: 'Danmarks Flyttemand ApS'
});
// Added custom event listener for availability of userPosition
$(document).one('userPositionAvailable', function(evt, userPos) {
if (userPos != null && userPos != '') {
addDirections(mapsCache[elem.id], userPos);
}
});
}
// Adds directions on gmap from userPos to a fixed position
var addDirections = function(gmap, userPos) {
var officePos = new google.maps.LatLng(55.689403, 12.521281); // fixed position
var userMarker = new google.maps.Marker({
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "green",
scale: 5
},
position: userPos,
map: gmap,
title: 'Your location'
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
directionsDisplay.setMap(gmap);
directionsDisplay.setPanel(document.getElementById('googledirections')); // add id here
var request = {
origin: userPos,
destination: officePos,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
//If we try to create a map before it is available
//listen to the event
if (!gmapsLoaded) {
$(document).one("gmaps:available", function () {
createMap()
});
} else {
createMap();
}
}
})(af);
function onGeoSuccess(position) {
var userPos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$(document).trigger('userPositionAvailable', userPos);
}
function onGeoError(error) {
navigator.notification.alert('Geolocation error: ' + error.message);
}
function initMaps() {
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(55.689403, 12.521281),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$('#googlemap').gmaps(mapOptions); // update id selector
$('#googlemap-panel').on('loadpanel', function() { // update event for other framework and id selector
$('#googlemap').gmaps('resize'); // update id selector
});
}
/@作者伊恩·马菲特
//@copyright App Framework 2012
//修改Rami@alphastagestudios.com - 2013
//-添加标记和方向
(功能(){
var gmapsload=false;//查看google maps API是否可用的内部变量
//我们在documentready上运行这个。如果它准备好了,它将触发一个gmaps:available事件
//或者它将为您提供谷歌地图脚本
$(文档).ready(函数(){
如果(窗口[“谷歌”]&&google.maps){
美元(文件).trigger(“gmaps:available”);
gmapsload=true;
返回true;
}
var gmaps=document.createElement(“脚本”);
gmaps.src=”http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&callback=gmapsPluginLoaded";
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<access origin="*" />
...
<feature name="http://api.phonegap.com/1.0/device"/>
<feature name="http://api.phonegap.com/1.0/geolocation"/>
<feature name="http://api.phonegap.com/1.0/notification"/>
map is %s, undefined
<script src="http://maps.google.com/maps/api/js?key=AIzaSyB1uhDdWjtNEl9K35lJtuq5Sw2BjKR8-OM&sensor=false" type="text/javascript"></script>
<code>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:windowSoftInputMode="adjustPan"
package="com.alphastagestudios.danmarksflyttemand" android:versionName="1.0" android:versionCode="2" android:hardwareAccelerated="true">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:hardwareAccelerated="true"
android:debuggable="true">
<activity android:name="DanmarksFlyttemandApp" android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17"/>
<permission android:name="com.alphastagestudios.danmarksflyttemand.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission android:name="com.alphastagestudios.danmarksflyttemand.permission.MAPS_RECEIVE"/>
</manifest>
</code>
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
body, html, #map-canvas {
width: 100%;
height: 400px;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
initMap();
}
// onError Callback receives a PositionError object
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var map,
userPosition,
officeLocation,
directionsDisplay,
directionsService;
function initMap() {
//directionsDisplay = new google.maps.DirectionsRenderer();
//directionsService = new google.maps.DirectionsService();
officeLocation = new google.maps.LatLng(55.689403, 12.521281);
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: officeLocation
};
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//directionsDisplay.setMap(map);
}
</script>
</head>
<body>
<p id="geolocation">Finding geolocation...</p>
<div id="map-canvas"></div>
</body>
</html>
// @author Ian Maffett
// @copyright App Framework 2012
// Modified by Rami@alphastagestudios.com - 2013
// - Added markers & directions
(function () {
var gmapsLoaded = false; //internal variable to see if the google maps API is available
//We run this on document ready. It will trigger a gmaps:available event if it's ready
// or it will include the google maps script for you
$(document).ready(function () {
if(window["google"]&&google.maps){
$(document).trigger("gmaps:available");
gmapsLoaded = true;
return true;
}
var gmaps = document.createElement("script");
gmaps.src = "http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&callback=gmapsPluginLoaded";
// Updated API url
$("head").append(gmaps);
window["gmapsPluginLoaded"] = function () {
$(document).trigger("gmaps:available");
gmapsLoaded = true;
}
});
//Local cache of the google maps objects
var mapsCache = {};
//We can invoke this in two ways
//If we pass in positions, we create the google maps object
//If we do not pass in options, it returns the object
// so we can act upon it.
$.fn.gmaps = function (opts) {
if (this.length == 0) return;
if (!opts) return mapsCache[this[0].id];
//Special resize event
if(opts=="resize"&&mapsCache[this[0].id])
{
var map = mapsCache[this[0].id];
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.setZoom(13);
// Extended resize to recenter and reset zoom
return map;
}
//loop through the items and create the new gmaps object
for (var i = 0; i < this.length; i++) {
new gmaps(this[i], opts);
}
};
//This is a local object that gets created from the above.
var gmaps = function (elem, opts) {
var createMap = function () {
var officePos = new google.maps.LatLng(55.689403, 12.521281);
if (!opts || Object.keys(opts).length == 0) {
opts = {
zoom: 13,
center: officePos,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
}
mapsCache[elem.id] = new google.maps.Map(elem, opts);
// Added marker for static location
var officeMarker = new google.maps.Marker({
position: officePos,
map: mapsCache[elem.id],
title: 'Danmarks Flyttemand ApS'
});
// Added custom event listener for availability of userPosition
$(document).one('userPositionAvailable', function(evt, userPos) {
if (userPos != null && userPos != '') {
addDirections(mapsCache[elem.id], userPos);
}
});
}
// Adds directions on gmap from userPos to a fixed position
var addDirections = function(gmap, userPos) {
var officePos = new google.maps.LatLng(55.689403, 12.521281); // fixed position
var userMarker = new google.maps.Marker({
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "green",
scale: 5
},
position: userPos,
map: gmap,
title: 'Your location'
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
directionsDisplay.setMap(gmap);
directionsDisplay.setPanel(document.getElementById('googledirections')); // add id here
var request = {
origin: userPos,
destination: officePos,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
//If we try to create a map before it is available
//listen to the event
if (!gmapsLoaded) {
$(document).one("gmaps:available", function () {
createMap()
});
} else {
createMap();
}
}
})(af);
function onGeoSuccess(position) {
var userPos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$(document).trigger('userPositionAvailable', userPos);
}
function onGeoError(error) {
navigator.notification.alert('Geolocation error: ' + error.message);
}
function initMaps() {
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(55.689403, 12.521281),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$('#googlemap').gmaps(mapOptions); // update id selector
$('#googlemap-panel').on('loadpanel', function() { // update event for other framework and id selector
$('#googlemap').gmaps('resize'); // update id selector
});
}
<access origin="*.google.com"/>
<access origin="*.googleapis.com"/>