Javascript:位置名称未更改,但数据已更改
我正在使用谷歌地图api和黑暗天空api创建一个天气应用程序。最初,当应用程序从localhost启动时(我只是使用一个python简单服务器),浏览器会获取用户的位置,并将其和相应的数据一起打印到屏幕上 但是,当我键入其他位置并点击搜索时,天气数据会发生变化,但位置保持不变 任何帮助都将不胜感激 JSJavascript:位置名称未更改,但数据已更改,javascript,api,geolocation,Javascript,Api,Geolocation,我正在使用谷歌地图api和黑暗天空api创建一个天气应用程序。最初,当应用程序从localhost启动时(我只是使用一个python简单服务器),浏览器会获取用户的位置,并将其和相应的数据一起打印到屏幕上 但是,当我键入其他位置并点击搜索时,天气数据会发生变化,但位置保持不变 任何帮助都将不胜感激 JS //全局变量 var地理位置={lat:40.7127837,lng:-74.0059413}; var city=‘纽约市’; $(文档).ready(函数(){ $(“#选定城市”)。按键(
//全局变量
var地理位置={lat:40.7127837,lng:-74.0059413};
var city=‘纽约市’;
$(文档).ready(函数(){
$(“#选定城市”)。按键(功能(e){
如果(e.which==13){
ajaxReqForLatLon();
setTimeout(函数(){
初始地图(地理定位);
}, 500);
}
});
//控制台日志(ajaxReqForLatLon);
$(“#搜索按钮”)。在('click',function()上{
ajaxReqForLatLon();
});
$('.btn.btn success.btn block')。在('click',function()上{
$(“#选定城市”).val(“”.focus();
});
//交通
//谷歌地图
函数ajaxReqForLatLon(){
var userRequestedLocation=selectedCity();
var googleApiURL=https://maps.googleapis.com/maps/api/geocode/json?address=';
googleApiURL+=userRequestedLocation;
googleApiURL+='&key=API_key';
$.ajax({
键入:“GET”,
网址:googleApiURL,
成功:功能(响应){
地理位置=GoogleAppSuccessHandler(响应);
天气数据();
},
错误:函数(jqXHR、textStatus、errorshown){
console.log(错误抛出);
}
});
}
//从ajax获取响应并获取地理位置信息
函数googleApiSuccessHandler(响应){
var geoLocation=response.results[0].geometry.location;
返回地理定位;
}
函数selectedCity(){
城市=$(“#所选城市”).val().trim();
如果(city.length==0){
$(“#选定城市”).addClass(“动画震动”);
$(“#选定城市”).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',function(){
$(“#选定城市”).removeClass(“动画震动”);
});
返回;
};
回归城市;
}
$(“#选定城市”)。按键(功能(e){
如果(e.which==13){
ajaxReqForLatLon();
setTimeout(函数(){
初始地图(地理定位);
}, 500);
}
});
//页面加载时的映射
setTimeout(函数(){
初始地图(地理定位);
}, 500);
var-triggerOnce=true;
函数initMap(地理位置){
var map=new google.maps.map(document.getElementById('map'){
缩放:12,
中心:地理定位,
滚轮:错误
});
var marker=new google.maps.marker({map:map});
如果(触发器){
triggerOnce=false;
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(函数(位置){
geoLocation.lat=位置坐标纬度;
geoLocation.lng=position.coords.longitude;
var pos={
纬度:位置坐标纬度,
lng:position.coords.longitude
};
反向编码();
天气数据();
setTimeout(函数(){
$(“.location”).html(城市);
}, 500);
标记器设置位置(pos);
地图设置中心(pos);
},函数(){
handleLocationError(true,marker,map.getCenter());
});
}否则{
handleLocationError(false,marker,map.getCenter());
}
}
功能手柄位置错误(浏览器有地理位置、标记、位置){
标记器设置位置(pos);
天气数据();
}
var trafficLayer=new google.maps.trafficLayer();
trafficLayer.setMap(地图);
}
//反向地理编码
函数reverseGeocode(){
var googleRevGeoApiURL=https://maps.googleapis.com/maps/api/geocode/json?latlng=';
googleRevGeoApiURL+=geoLocation.lat+','+geoLocation.lng;
googleRevGeoApiURL+='&key=AIzaSyCh5Q8_EFHuuQKVb4O3esOvemg-nFe6X0U';
$.ajax({
键入:“GET”,
url:googleRevGeoApiURL,
成功:功能(响应){
城市=响应。结果[0]。地址\组件[2]。长\名称;
},
错误:函数(jqXHR、textStatus、errorshown){
console.log(错误抛出);
}
});
}
//天气
var weatherData=函数(){
var geoLocLat=geoLocation.lat;
var geoLocLon=geoLocation.lng;
var forecastURL=https://api.forecast.io/forecast/80b1dfb6da9003b42f0dd846a0f08703/“+geoLocLat+”,“+geoLocLon;
var数据;
$.getJSON(forecastURL+'?回调=?',函数(数据){
$(“#weather').html('Today:'+data.Current.summary+'
'+'Current:'+data.Current.temperature.toFixed(0)+'°;F'+'
'+'High:'+data.daily.data[1].temperatureMax.toFixed(0)+'°;F');
});
};
});
HTML
搜寻
您是否已在调试器中仔细检查了它,以查看故障所在?如果您对调试器不满意,也许可以添加几行console.log来检查基本变量中的值,或者记录map.setCenter(pos)是否在您询问的用例中被触发。您是否在调试器中仔细检查了它以查看故障所在?如果不习惯使用调试器,也许您可以添加几行console.log来检查基本变量中的值,或者记录在您询问的用例中是否触发了map.setCenter(pos)
// Global Variables
var geoLocation = {lat: 40.7127837, lng: -74.0059413};
var city = 'New York City';
$(document).ready(function(){
$('#selected-city').keypress(function(e){
if(e.which == 13){
ajaxReqForLatLon();
setTimeout(function(){
initMap(geoLocation);
}, 500);
}
});
// console.log(ajaxReqForLatLon);
$('#search-button').on('click', function(){
ajaxReqForLatLon();
});
$('.btn.btn-success.btn-block').on('click', function(){
$('#selected-city').val("").focus();
});
// Traffic
// Google Maps
function ajaxReqForLatLon(){
var userRequestedLocation = selectedCity();
var googleApiURL = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
googleApiURL += userRequestedLocation;
googleApiURL += '&key=API_KEY';
$.ajax({
type: 'GET',
url: googleApiURL,
success: function(response){
geoLocation = googleApiSuccessHandler(response);
weatherData();
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
}
// take response from ajax and take the geolocation
function googleApiSuccessHandler(response){
var geoLocation = response.results[0].geometry.location;
return geoLocation;
}
function selectedCity(){
city = $('#selected-city').val().trim();
if(city.length === 0){
$('#selected-city').addClass('animated shake');
$('#selected-city').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$('#selected-city').removeClass('animated shake');
});
return;
};
return city;
}
$('#selected-city').keypress(function(e){
if(e.which == 13){
ajaxReqForLatLon();
setTimeout(function(){
initMap(geoLocation);
}, 500);
}
});
// Map on page load
setTimeout(function(){
initMap(geoLocation);
}, 500);
var triggerOnce = true;
function initMap(geoLocation){
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 12,
center: geoLocation,
scrollWheel: false
});
var marker = new google.maps.Marker({map : map});
if(triggerOnce){
triggerOnce = false;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
geoLocation.lat = position.coords.latitude;
geoLocation.lng = position.coords.longitude;
var pos = {
lat : position.coords.latitude,
lng : position.coords.longitude
};
reverseGeocode();
weatherData();
setTimeout(function(){
$(".location").html(city);
}, 500);
marker.setPosition(pos);
map.setCenter(pos);
}, function(){
handleLocationError(true, marker, map.getCenter());
});
} else {
handleLocationError(false, marker, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, marker, pos){
marker.setPosition(pos);
weatherData();
}
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
// Reverse Geocode
function reverseGeocode(){
var googleRevGeoApiURL = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=';
googleRevGeoApiURL += geoLocation.lat + ',' + geoLocation.lng;
googleRevGeoApiURL += '&key=AIzaSyCh5Q8_EFHuuQKVb4O3esOvemg-nFe6X0U';
$.ajax({
type: 'GET',
url: googleRevGeoApiURL,
success: function(response){
city = response.results[0].address_components[2].long_name;
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
}
// Weather
var weatherData = function(){
var geoLocLat = geoLocation.lat;
var geoLocLon = geoLocation.lng;
var forecastURL = 'https://api.forecast.io/forecast/80b1dfb6da9003b42f0dd846a0f08703/' + geoLocLat + ',' + geoLocLon;
var data;
$.getJSON(forecastURL + '?callback=?', function(data){
$('#weather').html('Today: ' + data.currently.summary + '<br>' + 'Currently: ' + data.currently.temperature.toFixed(0) + '° F' + '<br>' + 'High: ' + data.daily.data[1].temperatureMax.toFixed(0) + '° F');
});
};
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<br>
<input type="search" id="selected-city" class="form-control" placeholder="Enter City" autofocus>
<button id="search-button" class="btn btn-success btn-block" type="submit">Search</button>
<br>
<h2 class="location"></h2>
<h4 id="weather"></h4>
<div id="map"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCh5Q8_EFHuuQKVb4O3esOvemg-nFe6X0U&signed_in=true&callback=initMap" async defer></script>
<script type="text/javascript" src="meteocast.js"></script>
</body>
</html>