实际上我想让用户的当前位置跟踪其移动,是否可以在Asp.Net网络应用程序中?因为我需要在每秒或之后追踪它。我做了一个代码,它给我在localhost的纬度和经度,但没有在IP地址为什么?它给地图上的错误“出了问题”。代码如下 标题部分
<head runat="server">
<title></title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor"></script>
<script type="text/javascript">
function setText(val, e) {
document.getElementById(e).value = val;
}
function insertText(val, e) {
document.getElementById(e).value += val;
}
var nav = null;
function requestPosition() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
geoloc.getCurrentPosition(successCallback);
}
else {
alert("geolocation not supported");
}
}
else {
alert("Navigator not found");
}
}
function successCallback(position)
{
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
var latlng = new google.maps.LatLng(position.coords.latitude,
position.coords.latitude);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(position.coords.latitude,
position.coords.longitude),
map: map,
title: 'Click me'
}
);
}
</script>
</head>
现在身体部分是
<body>
<label for="latitude">Latitude: </label><input id="latitude" /> <br />
<label for="longitude">Longitude: </label><input id="longitude" /> <br />
<input type="button" onclick="requestPosition()" value="Get Latitude and Longitude" />
<div id="map" style="width:400px;height:400px">
</div>
</body>
答案 0 :(得分:0)
Mozilla的MDN网络为您的问题提供了一个非常好的解决方案示例:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
这在JSFiddle(https://jsfiddle.net/api/mdn/)中适用于我,但在下面的StackOverflow代码段中(至少在最新版本的Chrome中)没有。这可能是有关GeoLocation API的跨源策略的问题。
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=true";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
body {
padding: 20px;
background-color:#ffffc9
}
p { margin : 0; }
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>