Google Maps API GeoLocation不适用于移动设备 [英] Google Maps API GeoLocation not working for mobile

查看:111
本文介绍了Google Maps API GeoLocation不适用于移动设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定为什么GeoLocation可以在我的电脑上运行,但不是我的iPhone ...我在脚本中调用了 sensor = true API,但除此之外,我不知所措。以下是整个脚本:

I'm not really sure why the GeoLocation works on my PC, but not my iPhone ... I've got sensor=true within the script call to the API, but apart from that, I'm at a loss. Here's the entire script:

                <div id="info"></div>
                <div id="map_canvas" style="width:908px; height:420px"></div>
                <input type="text" id="addressInput" size="10"/>
                <select id="radiusSelect">
                    <option value="5" selected>5mi</option>
                    <option value="15" selected>15mi</option>
                    <option value="25" selected>25mi</option>
                    <option value="100">100mi</option>
                    <option value="200">200mi</option>
                    <option value="4000">4000mi</option>
                </select>
                <input type="button" value="Search" onclick="searchLocations();">
                <div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>                   

                <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCe49sI29q0AVNo9iVvQ-lDlDwZpFZuA4o&sensor=true"></script>
                <script type="text/javascript" src="http://gmaps-samples-v3.googlecode.com/svn/trunk/geolocate/geometa.js"></script>
                <script type="text/javascript">

                var map;
                var markers = [];
                var infoWindow;
                var locationSelect;

                function load() {
                    map = new google.maps.Map(document.getElementById("map_canvas"), {
                        center: new google.maps.LatLng(40, -100),
                        zoom: 4,
                        mapTypeId: 'roadmap',
                        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
                    });
                    infoWindow = new google.maps.InfoWindow();

                    locationSelect = document.getElementById("locationSelect");
                    locationSelect.onchange = function() {
                        var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
                        if (markerNum != "none") {
                            google.maps.event.trigger(markers[markerNum], 'click');
                        }
                    };

                    // geolocation
                    prepareGeolocation();
                    doGeolocation();
                }

                function doGeolocation() {
                    if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(positionSuccess, positionError);
                    } else {
                        positionError(-1);
                    }
                }

                function positionError(err) {
                    var msg;
                    switch(err.code) {
                        case err.UNKNOWN_ERROR:
                            msg = "Unable to find your location";
                            break;
                        case err.PERMISSION_DENINED:
                            msg = "Permission denied in finding your location";
                            break;
                        case err.POSITION_UNAVAILABLE:
                            msg = "Your location is currently unknown";
                            break;
                        case err.BREAK:
                            msg = "Attempt to find location took too long";
                            break;
                        default:
                        msg = "Location detection not supported in browser";
                    }
                    document.getElementById('info').innerHTML = msg;
                }

                function positionSuccess(position) {
                    // Centre the map on the new location
                    var coords = position.coords || position.coordinate || position;
                    var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
                    map.setCenter(latLng);
                    map.setZoom(15);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latLng,
                        title: 'Why, there you are!'
                    });
                    document.getElementById('info').innerHTML = 'Looking for <b>' +
                    coords.latitude + ', ' + coords.longitude + '</b>...';

                    // And reverse geocode.
                    (new google.maps.Geocoder()).geocode({latLng: latLng}, function(resp) {
                        var place = "You're around here somewhere!";
                        if (resp[0]) {
                            var bits = [];
                            for (var i = 0, I = resp[0].address_components.length; i < I; ++i) {
                                var component = resp[0].address_components[i];
                                if (contains(component.types, 'political')) {
                                    bits.push('<b>' + component.long_name + '</b>');
                                }
                            }
                            if (bits.length) {
                                place = bits.join(' > ');
                            }
                            marker.setTitle(resp[0].formatted_address);
                        }
                        document.getElementById('info').innerHTML = place;
                    });
                }

                function contains(array, item) {
                    for (var i = 0, I = array.length; i < I; ++i) {
                        if (array[i] == item) return true;
                    }
                    return false;
                }

                function searchLocations() {
                    console.log("searching locations...");
                    var address = document.getElementById("addressInput").value;
                    var geocoder = new google.maps.Geocoder();
                    geocoder.geocode({address: address}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            searchLocationsNear(results[0].geometry.location);
                        } else {
                            alert(address + ' not found');
                        }
                    });
                }

                function clearLocations() {
                    //infoWindow.close();
                    for (var i = 0; i < markers.length; i++) {
                        markers[i].setMap(null);
                    }
                    markers.length = 0;

                    locationSelect.innerHTML = "";
                    var option = document.createElement("option");
                    option.value = "none";
                    option.innerHTML = "See all results:";
                    locationSelect.appendChild(option);
                    locationSelect.style.visibility = "visible";
                }

                function searchLocationsNear(center) {
                    clearLocations();

                    var radius = document.getElementById('radiusSelect').value;
                    /* var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; */
                    var searchUrl = 'http://dev-imac.local/phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
                    console.log(searchUrl);
                    downloadUrl(searchUrl, function(data) {
                        var xml = parseXml(data);
                        var markerNodes = xml.documentElement.getElementsByTagName("marker");
                        var bounds = new google.maps.LatLngBounds();
                        for (var i = 0; i < markerNodes.length; i++) {
                            var name = markerNodes[i].getAttribute("name");
                            var address = markerNodes[i].getAttribute("address");
                            var distance = parseFloat(markerNodes[i].getAttribute("distance"));
                            var latlng = new google.maps.LatLng(
                                parseFloat(markerNodes[i].getAttribute("lat")),
                                parseFloat(markerNodes[i].getAttribute("lng")));

                                createOption(name, distance, i);
                                createMarker(latlng, name, address);
                                bounds.extend(latlng);
                        }
                        map.fitBounds(bounds);
                    });
                }

                function createMarker(latlng, name, address) {
                    var html = "<b>" + name + "</b> <br/>" + address;
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latlng
                    });
                    google.maps.event.addListener(marker, 'click', function() {
                        infoWindow.setContent(html);
                        infoWindow.open(map, marker);
                    });
                    markers.push(marker);
                }

                function createOption(name, distance, num) {
                    var option = document.createElement("option");
                    option.value = num;
                    option.innerHTML = name + "(" + distance.toFixed(1) + ")";
                    locationSelect.appendChild(option);
                }

                function downloadUrl(url, callback) {
                    var request = window.ActiveXObject ?
                    new ActiveXObject('Microsoft.XMLHTTP') :
                    new XMLHttpRequest;

                    request.onreadystatechange = function() {
                        if (request.readyState == 4) {
                            request.onreadystatechange = doNothing;
                            callback(request.responseText, request.status);
                        }
                    };

                    request.open('GET', url, true);
                    request.send(null);
                }

                function parseXml(str) {
                    if (window.ActiveXObject) {
                        var doc = new ActiveXObject('Microsoft.XMLDOM');
                        doc.loadXML(str);
                        return doc;
                    } else if (window.DOMParser) {
                        return (new DOMParser).parseFromString(str, 'text/xml');
                    }
                }

                function doNothing() {}

                window.onload = load();

                </script>


推荐答案

首先,

First of all,

mapTypeId: 'roadmap',

应该是:

should be:

mapTypeId: google.maps.MapTypeId.ROADMAP,

但是这也会导致它在PC上失败。

but that should cause it to fail in your PC as well.

除此之外,您的< script> 部分应位于文档的< head> 部分中,而不在<身体GT; 。也许iPhone浏览器比PC上的浏览器更严格。你在每个系统中使用什么浏览器? (我猜你在PC上使用IE浏览器,你是否尝试了其他浏览器?)

Other than that, your <script> section should be in the <head> section of the document and not in the <body>. Maybe the iPhone browser is more strict about this than the browser on your PC. What browser(s) are you using in each system? (I'm guessing you're using IE on the PC. Have you tried other browsers?)

这篇关于Google Maps API GeoLocation不适用于移动设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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