1

我的 JavaScript(如下)非常不整洁,并且包含一个我无法解决的错误。错误在 showPosition 函数内(我在函数中有一个函数,不推荐)。
我刚刚开始尝试使用 JavaScript,所以如果这是一个简单的问题,我深表歉意。我还提供了我的 JavaScript 的 jsFiddle,它突出显示了我坚持的区域 ( http://jsfiddle.net/dnUTx/ )。

在 jsFiddle 中,我在第 25 行收到错误 - “函数声明不应放在块中”。

任何帮助将不胜感激。

// JavaScript Document

var x = document.getElementById("info");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition, showError, clearWatch, {
            enableHighAccuracy: true,
            maximumAge: 30000,
            timeout: 30000
        });
    } else {
        x.innerHTML = "Your browser does not support the geolocation () API.";
    }
}
var flightPathCoordinates = [];
var lat1, lng1, first_check = false;

function showPosition(position) {
    if (!first_check) {
        lat1 = position.coords.latitude;
        lng1 = position.coords.longitude;
        first_check = true;
    } else {
        function distanceFrom(points) {
            var lat1 = points.lat1;
            var radianLat1 = lat1 * (Math.PI / 180);
            var lng1 = points.lng1;
            var radianLng1 = lng1 * (Math.PI / 180);
            var lat2 = points.lat2;
            var radianLat2 = lat2 * (Math.PI / 180);
            var lng2 = points.lng2;
            var radianLng2 = lng2 * (Math.PI / 180);
            var earth_radius = 3959; // or 6371 for kilometers
            var diffLat = (radianLat1 - radianLat2);
            var diffLng = (radianLng1 - radianLng2);
            var sinLat = Math.sin(diffLat / 2);
            var sinLng = Math.sin(diffLng / 2);
            var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);
            var distance = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));
            return distance.toFixed(3);
        }
        var distance = distanceFrom({
            "lat1": lat1,
            "lng1": lng1,
            "lat2": position.coords.latitude,
            "lng2": position.coords.longitude
        });
    }
    x.innerHTML = "Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude +
        "<br>Accuracy: " + position.coords.accuracy +
        "<br>Altitude: " + position.coords.altitude +
        "<br>Altitude Accuracy: " + position.coords.altitudeAccuracy +
        "<br>Heading: " + position.coords.heading +
        "<br>Speed (km): " + position.coords.speed * 3.6 +
        "<br>Timestamp: " + new Date(position.timestamp).toLocaleString() +
        "<br>Distance Travelled (km): " + distance +
        "<br>Stopwatch: " + min + ":" + sec + ":" + msec;

    lat = position.coords.latitude;
    lon = position.coords.longitude;
    latlon = new google.maps.LatLng(lat, lon);
    mapholder = document.getElementById('mapholder');

    var myOptions = {
        center: latlon,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);

    //Bicycle Store
    var request = {
        location: (latlon),
        radius: '1000',
        types: ['bicycle_store']
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);

    function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            for (var i = 0; i < results.length; i++) {
                var place = results[i];
                createMarker(results[i]);
            }
        }
    }

    function createMarker(place) {
        var placeLoc = place.geometry.location;

        //Custom Marker 1
        var image1 = '../images/logo_marker1.png';
        var marker1 = new google.maps.Marker({
            position: place.geometry.location,
            map: map,
            icon: image1,
            title: "Bicycle Store"
        });
        google.maps.event.addListener(marker1, 'click', function () {
            infowindow.setContent(place.name);
            infowindow.open(map, this);
        });
    }

    //Bicycle Layer
    var bikeLayer = new google.maps.BicyclingLayer();
    bikeLayer.setMap(map);

    //Custom Marker 2
    var image2 = '../images/logo_marker2.png';
    var marker2 = new google.maps.Marker({
        position: latlon,
        map: map,
        icon: image2,
        title: "You are here!"
    });

    //Panoramio Layer
    var panoramioLayer = new google.maps.panoramio.PanoramioLayer();

    panoramioLayer.setUserId("7467601");
    panoramioLayer.setMap(map);
    google.maps.event.addListener(panoramioLayer, 'click', function (event) {
        var attribution = document.createTextNode(event.featureDetails.title + ": " + event.featureDetails.author);
        var br = document.createElement("br");
        var link = document.createElement("a");
        link.setAttribute("href", event.featureDetails.url);
        link.appendChild(attribution);
    });

    //Polyline Layer
    flightPathCoordinates.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    var flightPath = new google.maps.Polyline({
        path: flightPathCoordinates,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    flightPath.setMap(map);
}

function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation.";
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable.";
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out.";
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred.";
            break;
    }
}

function clearWatch() {
    navigator.geolocation.clearWatch(showPosition);
}
4

1 回答 1

2

好吧,对我来说,这个问题非常清楚,甚至为新成员提供了一个 jsfiddle,+1。

你的问题是2倍:

您使用局部变量distance来构建您的x.innerHTML字符串。但是,distance仅在elseif 语句的子句中定义(精确分配)。

其次,您在 block 中使用“函数声明” {},这在语法上是非法的!这是因为 Blocks 只能包含 Statements,而不是 SourceElements,FunctionDeclaration 是。
因此,在 if/else/while/for 块中,您必须使用“函数表达式”;
例如:var identifier=function(//args){//code};
这就是 JSFiddle 中的 JSHint 给出的错误消息的原因。

请参阅此小提琴更新以查看我的更改(只是使 jshint 验证,但由于这只是某些代码的一部分,因此我无法进一步尝试)。

我在你的函数中var distance=0的第一个 - 子句之前添加了一个局部变量,并将你的 - 子句更改为一个内部变量。ifshowPositionfunction declarationfunction expressionelse

祝你好运!

于 2013-03-27T16:33:55.140 回答