-1

Im working with google maps so my whole app is basically a big google maps. This is the js-code i have in my view:

          <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>

and since there is some code that i can't put in a js-file like @sessionstore variable and the @request.isauthenticated properties i cannot move this code to a js-file.

Then i have my google maps code in a js-file like this:

     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);

So my problems is that in the view-js code i have a method that gets all the saved destinations in from the database and i want it to put a marker on the map for every on of them. So in the GetDestination() i want to put a marker on the map with this code:

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

the problem is that map is not created yet. It is created in the js-file. How do i structure this in a better way so that i can do the getdestination method after the map is created?

1
  • Put the code in a function and call the function when the map is created? Commented Apr 6, 2015 at 15:14

1 Answer 1

1

In your view JS, edit your getDestinations function. Move if statement in to function.

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);
            },
        });
    }
}

In Google Maps JS file add into initialize function.

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

If idle event dosen't work, try tilesloaded event.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.