wha*_*atf 14 javascript html5 google-maps geolocation ip-geolocation
我试图通过html5 geolcation api获取用户地理位置,我使用以下代码片段:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
// DO SOME STUFF HERE
}
function displayPosition(position) {
// configuration
var myZoom = 12;
var myMarkerIsDraggable = true;
var myCoordsLenght = 6;
var defaultLat = position.coords.latitude;
var defaultLng = position.coords.longitude;
document.getElementById('latitude').value = defaultLat;
document.getElementById('longitude').value = defaultLng;
/*
1. creates the map
2. zooms
3. centers the map
4. sets the map’s type
*/
var map = new google.maps.Map(document.getElementById('canvas'), {
zoom: myZoom,
center: new google.maps.LatLng(defaultLat, defaultLng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
// centers the map on markers coords
map.setCenter(myMarker.position);
// adds the marker on the map
myMarker.setMap(map);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
});
Run Code Online (Sandbox Code Playgroud)
上述方法的问题在于,很少有用户发现难以使用.几乎没有时间,他们点击了拒绝而不是允许并继续盯着屏幕.所以从可用性的角度来看,我认为一个好的方法是:
请他们许可.
等待3秒钟,如果他们点击拒绝或没有响应,请使用IP在地图上显示地理位置.
如何完成上述代码片段中的第二步.请让我知道,谢谢!但是,什么是更好的处理方式
Onu*_*rım 16
这是我前一段时间写过并最近更新的脚本(geolocator.js).
更新:Geolocator v2已发布.
var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30, // meters
fallbackToIP: true, // get location by IP if geolocation fails or rejected
addressLookup: true, // requires Google API key
timezone: true, // requires Google API key
map: "my-map" // creates a Google map. requires Google API key
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});
Run Code Online (Sandbox Code Playgroud)
示例输出:
{
coords: {
latitude: 37.4224764,
longitude: -122.0842499,
accuracy: 30,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null
},
address: {
commonName: "",
street: "Amphitheatre Pkwy",
route: "Amphitheatre Pkwy",
streetNumber: "1600",
neighborhood: "",
town: "",
city: "Mountain View",
region: "Santa Clara County",
state: "California",
stateCode: "CA",
postalCode: "94043",
country: "United States",
countryCode: "US"
},
formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
type: "ROOFTOP",
placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
timezone: {
id: "America/Los_Angeles",
name: "Pacific Standard Time",
abbr: "PST",
dstOffset: 0,
rawOffset: -28800
},
flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
map: {
element: HTMLElement,
instance: Object, // google.maps.Map
marker: Object, // google.maps.Marker
infoWindow: Object, // google.maps.InfoWindow
options: Object // map options
},
timestamp: 1456795956380
}
Run Code Online (Sandbox Code Playgroud)