在ReactJS中调用地理位置

时间:2015-03-03 19:49:35

标签: javascript jquery ajax html5 reactjs

我在这里有一个非常简单的天气应用程序的代码,但我希望它能够使用返回的用户经纬度来定位地理定位并构建对wunderground API的ajax调用。该应用程序到目前为止:

var WeatherApp = React.createClass({
    getInitialState: function () {
        return {};
    },
    componentDidMount: function () {
        var vm = this; 
        var url = "https://api.wunderground.com/api/[apikey]/geolookup/conditions/q/IA/Cedar_Rapids.json";
        var getWeather = function (res) {
            // Update component 
            if (vm.isMounted()) {
                var obv = res["current_observation"];
                vm.setState(obv);
            } else {
                console.log(res.text);
            }
        }
        $.ajax({
            url: url,
            dataType: "jsonp"
        }).done(getWeather);
    },
    render: function () {
        var weather = this.state.weather;
        var temp = this.state.temp;
        return (
            <div>
                <Sphere weather={ weather } temp={ temp }/>
            </div>
        );
    }
});
  

var Sphere = React.createClass({
    render: function () {
        var skyClass = this.props.temp > 30 ? "sun" : "clouds";
        return (
            <div>
                <div className={ skyClass }></div>
                <div>{this.props.weather}</div>
            </div>
        )
    }
});

React.render(<WeatherApp />, document.body);

我有这个vanilla js函数来使用geolocation来构建url

var x = document.getElementById("location");
function requestCurrentPosition(){
        if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(useGeoData);
        }
}

 function useGeoData(position){
   x.innerHTML = (" http://api.wunderground.com/api/[apikey]/geolookup/q/" + position.coords.latitude + "," + position.coords.longitude + ".json");
  };
requestCurrentPosition();

...但是如何将输出网址转换为我的$ ajax调用可以访问的React prop?

0 个答案:

没有答案