在HTML,CSS,JS中为Windows PHONE 8.1映射API

时间:2014-07-16 20:41:27

标签: javascript html windows-phone-8.1 bing-maps

我知道有一个类似的问题(Map APIs not working for windows phone in HTML),但我没有足够的声誉来评论,所以我不得不问自己的问题。

我已成功将bing贴图添加到我的Windows 8.1商店应用程序(HTML,JS,CSS),但是当尝试将visual studio中的引用(地图SDK)添加到Windows Phone 8.1时,我无法使用该选项。我查看了之前提出的问题的答案,在示例中有一个Windows应用商店应用程序(很好!),一个移动网络应用程序和一个C#示例。所以我尝试了移动网络版,但只是添加了这个链接

<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&mkt=en-gb"></script> 

显然会给出错误,即您无法将远程脚本添加为本地远程脚本(沿着这些行添加)

所以我尝试从上面的url复制代码并在本地保存,但这给了我关于脚本试图注入动态内容的错误。现在我对于接下来要尝试的内容有点松散...任何有用内容的建议/链接都将非常感谢!

我应该提一下,我已经看过很多关于添加地图的文档,并且它们都包含在windows phone 8.1 sdk中,所以你不需要bing maps sdk但是这些主要是xaml,有没有办法访问sdk通过js?

3 个答案:

答案 0 :(得分:0)

因为Bing Maps Extension仅适用于Windows 8.1应用程序(希望它们能够更新它...),并且因为您无法在WinJS页面控件中包含外部JS库引用,所以这就是你可以获得Bing Maps的方法在WP8.1 HTML / JS应用程序上工作:

在您的Page Control html中插入一个webview,如:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>mapcontrol</title>

</head>
<body>
    <div class="mapcontrol fragment">
        <section id="mapcanvas" class="" aria-label="Main content" role="main">
            <x-ms-webview id="Map" style="width:100%; height:100%"></x-ms-webview>
        </section>
    </div>
</body>
</html>

创建一个HTML页面和一个JS文件,并放置创建地图所​​需的所有代码:

HTML页面(一个WP8源代码示例的副本):

<!DOCTYPE html>
<html>
<head>
<title>Bing Map</title>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx? v=7.0&mkt=en-gb"></script>
<script type="text/javascript" src="/pages/bingmap/bingmap.js"></script>
</head>
<body>
<div id="mapContainer">
    <div id='myMap'></div>
    <div class="appBar">
        <div class="appBarContainer">
            <img id="searchBtn" src="images/search.png" alt="searchBtn" />
            <img id="gpsBtn" src="images/gps.png" alt="gpsBtn" />
            <img id="trafficBtn" src="images/traffic.png" alt="trafficBtn" />
            <img id="mapModeBtn" src="images/layers.png" alt="mapModeBtn" />
        </div>
    </div>
    <div id="navBar">
        <img id="upBtn" src="images/up.png" alt="upBtn" />
        <img id="leftBtn" src="images/left.png" alt="leftBtn" />
        <img id="rightBtn" src="images/right.png" alt="rightBtn" />
        <img id="downBtn" src="images/down.png" alt="downBtn" />
    </div>
    <div id="zoomRotateBar">
        <img id="zoomInBtn" src="images/zoomIn.png" alt="zoomInBtn" />
        <img id="zoomOutBtn" src="images/zoomOut.png" alt="zoomOutBtn" />
        <div id="rotationBtns">
            <img id="rotateCWBtn" src="images/cwRotation.png" alt="rotateCWBtn" />
            <img id="rotateCCWBtn" src="images/ccwRotation.png" alt="rotateCCWBtn" />
        </div>
    </div>
</div>

<div id="searchPanel" style="display:none;">
    <h2>Search</h2>
    <input type="text" id="searchTbx" />
</div>

<div id="mapModePanel" style="display:none;">
    <h2>Map Mode</h2>

    <ul>
        <li>
            <input type="radio" name="mapMode" id="autoMode" value="auto" checked="checked" />
            <label for="autoMode">Auto</label>
        </li>
        <li>
            <input type="radio" name="mapMode" id="aerialMode" value="aerial" />
            <label for="aerialMode">Aerial</label>
        </li>
        <li>
            <input type="radio" name="mapMode" id="birdseyeMode" value="birdseye" />
            <label for="birdseyeMode">Birdseye</label>
        </li>
        <li>
            <input type="radio" name="mapMode" id="osMode" value="os" />
            <label for="osMode">Ordnance Survey</label>
        </li>
        <li>
            <input type="radio" name="mapMode" id="roadMode" value="road" />
            <label for="roadMode">Road</label>
        </li>
    </ul>
</div>
</body>
</html>

此页面的JS代码(示例源的副本):

(function () {
    var map,
    searchManager,
    geoLocationProvider,
    gpsLayer,
    gpsEnabled = false,
    trafficLayer,
    trafficEnabled = false;

// INIZIO INIT
function init() {

    getMap();

    //Test for multi-touch support
    if (navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1) {
        //Hide zoom and rotate controls
        document.getElementById('zoomRotateBar').style.display = 'none';
    } else {
        //Only display rotation buttons when the map style is birdseye
        Microsoft.Maps.Events.addHandler(map, 'maptypechanged', updateNavBar);
        Microsoft.Maps.Events.addHandler(map, 'viewchangeend', updateNavBar);

        //Add zooming and rotating functionality
        addListener(document.getElementById('zoomInBtn'), 'click', function () {
            map.setView({ zoom: map.getZoom() + 1 });
        });

        addListener(document.getElementById('zoomOutBtn'), 'click', function () {
            map.setView({ zoom: map.getZoom() - 1 });
        });

        addListener(document.getElementById('rotateCWBtn'), 'click', function () {
            map.setView({ heading: map.getHeading() + 90 });
        });

        addListener(document.getElementById('rotateCCWBtn'), 'click', function () {
            map.setView({ heading: map.getHeading() - 90 });
        });
    }

    //Test for single-touch support
    if (navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 0) {
        //Hide navigation controls
        document.getElementById('navBar').style.display = 'none';
    } else {
        //Add panning functionality
        addListener(document.getElementById('upBtn'), 'click', function () {
            map.setView({ center: map.getCenter(), centerOffset: new Microsoft.Maps.Point(0, 100) });
        });

        addListener(document.getElementById('leftBtn'), 'click', function () {
            map.setView({ center: map.getCenter(), centerOffset: new Microsoft.Maps.Point(100, 0) });
        });

        addListener(document.getElementById('rightBtn'), 'click', function () {
            map.setView({ center: map.getCenter(), centerOffset: new Microsoft.Maps.Point(-100, 0) });
        });

        addListener(document.getElementById('downBtn'), 'click', function () {
            map.setView({ center: map.getCenter(), centerOffset: new Microsoft.Maps.Point(0, -100) });
        });
    }

    addListener(document.getElementById('searchBtn'), 'click', function () {
        document.getElementById('searchPanel').style.display = '';
        document.getElementById('searchTbx').focus();
    });

    addListener(document.getElementById('searchTbx'), 'keydown', function (e) {
        if (!e) {
            e = window.event;
        }

        //process search when enter key pressed
        if (e.keyCode == 13) {
            search(this.value);
        }
    });

    addListener(document.getElementById('gpsBtn'), 'click', toggleGPS);

    addListener(document.getElementById('trafficBtn'), 'click', toggleTraffic);

    addListener(document.getElementById('mapModeBtn'), 'click', function () {
        document.getElementById('mapModePanel').style.display = '';
    });

    var mapModeBtns = document.getElementsByName('mapMode');

    for (var i = 0; i < mapModeBtns.length; i++) {
        addListener(mapModeBtns[i], 'click', function () {
            setMapMode(this.value);

            document.getElementById('mapModePanel').style.display = 'none';
        });
    }
}
// FINE INIT



function getMap() {
    var mapOptions = {
        credentials: "YOUR BING MAPS KEY",
        showDashboard: false,
        showCopyright: false,
        showScalebar: false,
        enableSearchLogo: false,
        enableClickableLogo: false,
        backgroundColor: new Microsoft.Maps.Color(255, 0, 0, 0)
    };

    // Initialize the map
    map = new Microsoft.Maps.Map(document.getElementById("myMap"), mapOptions);

    gpsLayer = new Microsoft.Maps.EntityCollection();
    map.entities.push(gpsLayer);
}

function updateNavBar() {
    if (map.isRotationEnabled()) {
        document.getElementById('rotationBtns').style.display = '';
    } else {
        document.getElementById('rotationBtns').style.display = 'none';
    }
}

function search(query) {
    if (searchManager) {
        var request = {
            where: query,
            count: 1,
            callback: geocodeCallback,
            errorCallback: geocodeError
        };

        searchManager.geocode(request);
    } else {
        //Load the Search module and create a search manager.
        Microsoft.Maps.loadModule('Microsoft.Maps.Search', {
            callback: function () {
                //Create the search manager
                searchManager = new Microsoft.Maps.Search.SearchManager(map);

                //Perfrom search logic
                search(query);
            }
        });
    }
}

function geocodeCallback(response, userData) {
    if (response &&
        response.results &&
        response.results.length > 0) {
        var r = response.results[0];
        var l = new Microsoft.Maps.Location(r.location.latitude, r.location.longitude);

        //Display result on map        
        var p = new Microsoft.Maps.Pushpin(l);
        map.entities.push(p);

        //Zoom to result
        map.setView({ center: l, zoom: 15 });
    } else {
        showMessage("Not results found.");
    }

    document.getElementById('searchPanel').style.display = 'none';
}

function geocodeError(request) {
    showMessage("Unable to Geocode request.");

    document.getElementById('searchPanel').style.display = 'none';
}

function toggleGPS() {
    gpsEnabled = !gpsEnabled;

    // Initialize the location provider
    if (!geoLocationProvider) {
        geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
    }

    //Clear the GPS layer 
    gpsLayer.clear();

    if (gpsEnabled) {
        // Get the user's current location
        geoLocationProvider.getCurrentPosition({
            successCallback: function (e) {
                gpsLayer.push(new Microsoft.Maps.Pushpin(e.center));
            },
            errorCallback: function (e) {
                showMessage(e.internalError);
            }
        });
    } else {
        //Remove the accuracy circle and cancel any request that might be processing
        geoLocationProvider.removeAccuracyCircle();
        geoLocationProvider.cancelCurrentRequest();
    }
}

function toggleTraffic() {
    trafficEnabled = !trafficEnabled;

    //Check to see if the traffic layer exists
    if (trafficLayer) {
        if (trafficEnabled) {
            trafficLayer.show();
        } else {
            trafficLayer.hide();
        }
    } else {
        //Load the traffic module and create the traffic layer.
        Microsoft.Maps.loadModule('Microsoft.Maps.Traffic', {
            callback: function () {
                //Create the traffic layer
                trafficLayer = new Microsoft.Maps.Traffic.TrafficLayer(map);

                //Get the base tile layer and set the opacity
                var layer = trafficLayer.getTileLayer();
                layer.setOptions({ opacity: 0.5 });

                trafficLayer.show();
            }
        });
    }
}

function setMapMode(mode) {
    var m;

    switch (mode) {
        case 'auto':
            m = Microsoft.Maps.MapTypeId.auto;
            break;
        case 'aerial':
            m = Microsoft.Maps.MapTypeId.aerial;
            break;
        case 'birdseye':
            m = Microsoft.Maps.MapTypeId.birdseye;
            break;
        case 'os':
            m = Microsoft.Maps.MapTypeId.ordnanceSurvey;
            break;
        case 'road':
        default:
            m = Microsoft.Maps.MapTypeId.road;
            break;
    }

    map.setView({ mapTypeId: m });
}

function showMessage(msg) {
    try {
        alert(msg);
    }
    catch (e) {
        if (Windows != null &&
            Windows.UI != null &&
            Windows.UI.Popups != null) {
            var popup = Windows.UI.Popups.MessageDialog(msg);
            popup.showAsync();
        }
    }
}

//Cross browser support for adding events. Mainly for IE7/8
function addListener(element, eventName, eventHandler) {
    if (element.addEventListener) {
        element.addEventListener(eventName, eventHandler, false);
    } else if (element.attachEvent) {
        if (eventName == 'DOMContentLoaded') {
            eventName = 'readystatechange';
        }
        element.attachEvent('on' + eventName, eventHandler);
    }
}

addListener(document, 'DOMContentLoaded', init);
})();

(使用Bing Maps Developer Key更改“您的BING MAPS KEY”) 然后在您的Page Control JS代码中导航到webview中托管的页面:

// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

var ControlConstructor = WinJS.UI.Pages.define("/pages/mapcontrol/mapcontrol.html", {
    // This function is called whenever a user navigates to this page. It
    // populates the page elements with the app's data.
    ready: function (element, options) {
        //// TODO: Initialize the page here.


        var webview = document.getElementById("Map");
        webview.navigate("ms-appx-web:///pages/bingmap/bingmap.html");


    },


});

})();

答案 1 :(得分:0)

使用您引用的Bing Maps JavaScript控件在WP8和8.1中可以正常工作。我整理了一个跨平台的代码示例,该示例适用于WP,Win8和Web,并在此处提供:http://code.msdn.microsoft.com/Cross-Platform-Bing-Maps-e96600d5

答案 2 :(得分:0)

实际上你可以将Win8.1的bing APi添加到WP8.1,只需破解bing map APi dll并将文件设置为Visual Studio并添加这样的引用

 <!-- Bing Maps references -->
<script type="text/javascript" src="/Bing.Maps.JavaScript/js/veapicore.js"></script>
<script type="text/javascript" src="/Bing.Maps.JavaScript/js/veapiModules.js"></script>

Screen capture

然后在使用Win8.1时正常工作, 看我的项目。顺便说一下,添加一个代码来验证连接状态,只有当连接退出时才会使这个地图工作(如果你手动添加一些图钉,它可以在没有连接的情况下工作)

Fair Of Sfax WP