构造js代码错误

时间:2015-04-06 15:06:30

标签: javascript google-maps google-maps-api-3

我正在使用谷歌地图,所以我的整个应用程序基本上是一个大的谷歌地图。 这是我认为的js-code:

          <script>
        $(document).ready(function () {
            var window = $("#mapWindow").data("kendoWindow");
            window.center();
            console.log('@Request.IsAuthenticated');
            if ('@Request.IsAuthenticated' == 'False') {
                getLoginContent();
                console.log("False");
            }
            if ('@SessionStore.CurrentBlogId' == 0 && '@Request.IsAuthenticated' == 'True') {
                getNewBlogContent();
                console.log("Blogid 0 and true");
            }
            if ('@SessionStore.CurrentBlogId' > 0 && '@Request.IsAuthenticated' == 'True') {
                getDestinations();
                console.log("Blogid > 0 true");
            }


            console.log('@SessionStore.CurrentBlogId');

            function getNewBlogContent() {
                $.ajax({
                    url: '@Url.Action("NewBlog", "Home")',
                    type: 'GET',
                    dataType: 'html',
                    cache: false,
                    success: function (data) {
                        $("#mapWindow").html(data);
                        window.title("Create Blog");
                        window.open();
                    },
                    error: function (xhr, error) {
                    },
                });
            }


            function getLoginContent() {
                $.ajax({
                    url: '@Url.Action("Login", "Account")',
                    type: 'GET',
                    dataType: 'html',
                    cache: false,
                    success: function(data) {
                        $("#mapWindow").html(data);
                        window.title("Login");
                        window.open();
                    },
                    error: function(xhr, error) {
                    },
                });
            }

            function getDestinations() {
                $.ajax({
                    url: '@Url.Action("GetDestinations", "Home")',
                    type: 'POST',
                    dataType: 'JSON',
                    cache: false,
                    success: function (data) {
                        console.log(data);
                        for (destination in data) {
                            console.log(data[destination]);
                            var latlng = { lat: data[destination].Latitude, lng: data[destination].Longitude }
                            console.log(latlng);
                            console.log(map);
                            var marker = new google.maps.Marker({
                                map: map,
                                postion: new google.maps.LatLng(latlng.lat, latlng.lng),
                            });


                            marker.setIcon(/** {google.maps.Icon} */({
                                url: '/Content/Markers/green_MarkerX.png',
                                size: new google.maps.Size(71, 71),
                                origin: new google.maps.Point(0, 0),
                                anchor: new google.maps.Point(17, 34),
                                scaledSize: new google.maps.Size(35, 35)
                            }));
                            marker.setPosition(latlng);
                            marker.setVisible(true);
                        }
                    },
                    error: function (xhr, error) {
                        console.log(error);
                    },
                });
            }


        });
    </script>

并且因为有一些代码我无法放入像@sessionstore变量这样的js文件和@ request.isauthenticated属性,所以我无法将此代码移动到js文件中。

然后我把我的谷歌地图代码放在一个像这样的js文件中:

     var map;

function initialize() {
    var mapCanvas = document.getElementById('map-canvas');
    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    }
    map = new google.maps.Map(mapCanvas, mapOptions);


    var input = document.getElementById('geoAutocomplete');
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new InfoBubble({
        map: map,
        position: new google.maps.LatLng(-32.0, 149.0),
        shadowStyle: 1,
        padding: 0,
        backgroundColor: 'rgb(57,57,57)',
        borderRadius: 5,
        arrowSize: 10,
        borderWidth: 1,
        borderColor: '#2c2c2c',
        disableAutoPan: true,
        hideCloseButton: true,
        arrowPosition: 30,
        backgroundClassName: 'transparent',
        arrowStyle: 2
    });


    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        infowindow.close();
        var marker = new google.maps.Marker({
            map: map,
            anchorPoint: new google.maps.Point(0, -29),
        });

        marker.setVisible(false);
        var place = autocomplete.getPlace();
        console.log(place);
        if (!place.geometry) {
            return;
        }


        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  // Why 17? Because it looks good.
        }
        marker.setIcon(/** @type {google.maps.Icon} */({
            url: '/Content/Markers/green_MarkerX.png',
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        console.log("position: " + place.geometry.location);
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);

        var address = '';
        if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }

        infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
        infowindow.open(map, marker);
        var longitude = place.geometry.location.D.toFixed(2);
        var latitude = place.geometry.location.k.toFixed(2);

        var countryIndex = place.address_components.length - 1;
        $.ajax({
            url: '/Home/AddDestination',
            type: 'POST',
            dataType: 'html',
            cache: false,
            data:{
                destinationName: place.name,
                countryCode: place.address_components[countryIndex].short_name,
                continentCode: getContinent(place.address_components[countryIndex].short_name),
                longitude: longitude.replace(".", ","),
                latitude: latitude.replace(".", ",")
    },
            success: function (data) {
                console.log(data);
            },
            error: function (xhr, error) {
            },
        });
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

所以我的问题是在view-js代码中我有一个方法可以从数据库中获取所有已保存的目标,并且我希望它在地图上为每个目标放置一个标记。所以在GetDestination()中我想用这段代码在地图上放置一个标记:

  var marker = new google.maps.Marker({
                                map: map,
                                postion: new google.maps.LatLng(latlng.lat, latlng.lng),
                            });

问题是还没有创建地图。它是在js文件中创建的。我如何以更好的方式构建它,以便我可以在创建地图后执行getdestination方法?

1 个答案:

答案 0 :(得分:1)

在您的视图JS中,编辑 getDestinations 功能。将if语句移到函数中。

function getDestinations() {
    if ('@SessionStore.CurrentBlogId' > 0 && '@Request.IsAuthenticated' == 'True') {
        console.log("Blogid > 0 true");

        $.ajax({
            url: '@Url.Action("GetDestinations", "Home")',
            type: 'POST',
            dataType: 'JSON',
            cache: false,
            success: function (data) {
                console.log(data);
                for (destination in data) {
                    console.log(data[destination]);
                    var latlng = { lat: data[destination].Latitude, lng: data[destination].Longitude }
                    console.log(latlng);
                    console.log(map);
                    var marker = new google.maps.Marker({
                        map: map,
                        postion: new google.maps.LatLng(latlng.lat, latlng.lng),
                    });


                    marker.setIcon(/** {google.maps.Icon} */({
                        url: '/Content/Markers/green_MarkerX.png',
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(35, 35)
                    }));
                    marker.setPosition(latlng);
                    marker.setVisible(true);
                }
            },
            error: function (xhr, error) {
                console.log(error);
            },
        });
    }
}

在Google Maps JS文件中添加初始化功能。

google.maps.event.addListenerOnce(map, 'idle', function(){
    // Get destinations after maps is loaded
    getDestinations();
});

如果idle事件不起作用,请尝试tilesloaded事件。