PhoneGap的+谷歌地图API第3版:不显示(所有)在Android [英] PhoneGap + Google Maps API v3 : Not displaying (at all) on Android

查看:363
本文介绍了PhoneGap的+谷歌地图API第3版:不显示(所有)在Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的现状

我目前正在开发一个客户,谁希望有一个谷歌地图集成的应用程序。他希望在地图上显示来自任何地方的用户是到他的办公室的路线。

I'm currently developing an app for a customer, who wishes to have a Google Maps integration. He wants the map to show the route from wherever the user is to his office.

我工作在Windows 8中,没有任何的IDE(用崇高的文本2)。

I'm working on a Windows 8, without any IDE (using Sublime Text 2).

我已经成功地得到它的工作一)在我的Chrome浏览器在本地,B)的纹波仿真器的PhoneGap /科尔多瓦> 2.0.0。然而,这根本就不是我的Andr​​oid手机(HTC感觉)每当我尝试的工作。它我发疯,我只是放弃它,并找到一些其他的,笨的解决方案(如静态地图或地理:URL接口)。

I've managed to get it working a) in my Chrome browser locally, b) in the Ripple Emulator for PhoneGap/Cordova >2.0.0. However, it simply will not work on my Android phone (HTC Sensation) whenever I try. It's driving me nuts and I'm just about to drop it and find some other, "dumber" solution (like a static map or the geo:url interface).

在我试图实际执行地图,我跑了PhoneGap的地理位置完整的例子,发现的此处。我注意到,我的Andr​​oid手机没有正确显示我的当前位置(经纬度/长/时间戳等)。因此,我认为,正确的权限(位置 - >等)被设定在我的手机

Before I tried to actually implement the map, I ran the the PhoneGap Geolocation full example, found here. I noted that my Android Phone did display my current position (lat/long/timestamp etc.) correctly. Thus, I believe that the correct permissions (Location -> etc.) has been set on my phone.

问题

谷歌地图不显示在所有的Andr​​oid设备。我看到了红色背景(调试),所以我知道的高度和宽度都很好。但我没有看到谷歌地图的任何迹象(没有按键,覆盖,网格或任何东西)。

Google Maps does not show up at all on my Android Device. I see the red background (for debugging), so I know the height and width are fine. But I do not see any sign of google maps (no buttons, overlays, grids or anything).

的code

HTML code加载了jQuery,科尔多瓦和地图API V3:

HTML code for loading jQuery, Cordova and Maps API v3:

<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>

这是HTML我用来放置地图:

This is the HTML I use to place the map:

<div id="map-canvas"
    style="display:block;
            overflow:hidden;
            position:relative;
            border:1px solid #aaaaaa;
            width: 100%;
            height: 400px;
            background: red;">
</div>
<div id="map-panel" style="width:100%; height:90%; position:relative; "></div>

这里是我的全谷歌地图JS(​​在它自己的文件):

And here is my full Google Maps JS (in its own file):

var map,
    userPosition,
    officeLocation,
    directionsDisplay,
    directionsService;

google.maps.event.addDomListener(window, 'load', setup);

function setup() {
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {
        navigator.geolocation.getCurrentPosition(onSuccess, onError, {enableHighAccuracy:true});
    }
}

function onSuccess(position) {
    userPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    navigator.notification.alert("Found user position");

    initializeMaps();
    //$('#map-canvas').css({'height': $(window).height()/2, 'width': '99%'});
}

function onError(error) {
    navigator.notification.alert("code: " + error.code + ",\n" +
                                 "message: " + error.message);
}

function initializeMaps() {
    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);

    if (userPosition != '') {
        var userPosMarker = new google.maps.Marker({
            position: userPosition,
            map: map,
            title: "Din Placering"
        });

        calculateRoute();
    }
    else {
        navigator.notification.alert("userPosition is null");
    }
}

function calculateRoute() {
    //navigator.notification.alert("calculateRoute");
    var request = {
        origin: userPosition,
        destination: officeLocation,
        travelMode: google.maps.DirectionsTravelMode["DRIVING"]
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setPanel(document.getElementById('map-panel'));
            directionsDisplay.setDirections(response);

            //navigator.notification.alert("Show directions");
        }
        else {
            navigator.notification.alert("Got status NOT OK from google");
        }
    });
}

function reloadGoogleMap() {
    if (map === null || map === undefined) {
        navigator.notification.alert("map is %s", map);
    }
    else {
        var currCenter = map.getCenter();
        google.maps.event.trigger(map, "resize");
        map.setCenter(currCenter);
        map.setZoom(12);
        //navigator.notification.alert("reloaded map");
    }
}

这是我的初始code(放在我的头底部的标记):

This is my initialization code (placed at the bottom of my head tag):

<script type="text/javascript" charset="utf-8">
    //navigator.notification.alert("listen for deviceready");
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {
        //navigator.notification.alert("device ready");
        ... 
        // calls other initialization functions
        ...
        initMaps();
        ..
    }
</script>

和我在AndroidManifest.xml中有这些(及其他):

And I have these (among others) in my AndroidManifest.xml:

<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" />

和我在config.xml中有这些(位于/assets/www/config.xml):

And I have these in my config.xml (located in /assets/www/config.xml):

<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"/>

这似乎是我的,我的的onSuccess方法不会被调用,但我没有看到任何警报,说明该用户的位置是无效的。事实上,在我的手机只通知我的执行的看到的是:

map is %s, undefined

在波动模拟器我得的发现用户位置每当我加载的应用程序。

In the ripple emulator I get the "Found user position" whenever I load the app.

请帮忙!

我忘了提,我使用Adobe的 http://build.phonegap.com 实际构建应用程序。

I forgot to mention that I'm using Adobe's http://build.phonegap.com to actually build the application.

我现在尝试使用谷歌API密钥就像这样:

I now tried to use Google API key like so:

<script src="http://maps.google.com/maps/api/js?key=AIzaSyB1uhDdWjtNEl9K35lJtuq5Sw2BjKR8-OM&sensor=false" type="text/javascript"></script>

但很可惜,没有任何变化。仍然一无所获。

But alas, no change. Still nothing.

下面是我的全的Andr​​oidManifest.xml

<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>

我现在试着建设有PhoneGap的地理定位和基本的谷歌地图一个小例子。我通过手动与Eclipse的科尔多瓦v内建了。2.9.0(最新的)。 奇怪的是,自己的PhoneGap的地理位置代码工作正常,但是当我介绍了谷歌地图code这一切停止工作。我试图使用和不使用谷歌API密钥这个最小的例子。没有什么区别。

I now tried building a minimal example with PhoneGap geolocation and a basic google map. I built it manually through Eclipse with Cordova v. 2.9.0 (the newest). Weird thing is, the PhoneGap geolocation example on its own worked fine, but when I introduce google maps code it all stopped working. I tried this minimal example with and without the google API key. No difference.

这是我用的是index.html的:

This is the index.html I was using:

<!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>

现在我已经尝试建立与PhoneGap的(科尔多瓦)诉申请。 2.6.0,2.9.0和2.8.1 - 没有工作。这款手机的地理位置工作正常,但谷歌地图显示不出来。我只看到了它应该是默认的灰色背景。

I have now attempted to build the application with PhoneGap (Cordova)v. 2.6.0, 2.9.0 and 2.8.1 - none worked. The phone's geolocation works fine, but google maps does not show up. I only see the default grey background of where it should be.

推荐答案

我从来没有解决了这个直接,但我开始使用的英特尔的应用程序框架,其中有一个例子插件谷歌地图(原文链接已经死了,看到编辑下文)。这个插件的伟大工程,对我来说,我是能够增加的方向吧。

I never solved this directly, but I started using Intel's App Framework, which had an example plugin for google maps (the original link is dead, see edit below). This plugin works great for me and I was able to add directions to it.

在code我结束了使用如下。没有权限或任何其他调整需要。请参见code中的意见。地图会出现无论地理位置成功或错误的,但如果它得到当前位置它增加指示到地图。否则,它显示了一个静点。

The code I ended up using is below. No permissions or any other adjustments needed. See the comments in the code. The map will show up regardless of geolocation success or error, but if it gets the current position it adds directions to the map. Otherwise it shows a static point.

// @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
    });
}

它出现的例子插件原来的链接是死了,所以这里是一个快速发现的新的链接(未经测试,仅仅是略快):的新的谷歌地图插件演示了英特尔的App-框架

It appears the original link for the example plugin is dead, so here is a quickly-found new link (untested and only skimmed quickly): New Google Maps Plugin Demo for Intel's App-Framework

这篇关于PhoneGap的+谷歌地图API第3版:不显示(所有)在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆