Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue rendering Google maps on 2nd render In Dialog Box

I have a website that i have built that is 90% jQuery with ajax so i would like to render different maps with directions with the click of a button without page refreshing.

I have everything working right for the first rendering as you can see in the following picture.

enter image description here

But when i go to reload or change to a different one i Get this: (I think it is still rendering the map with the points. just canvas is not right)

enter image description here

here is my code for the mapping:

window.initialize_map = function() {
    function getMiles(i) {
        return i*0.000621371192;
    }
    function toHHMMSS(i) {
        var sec_num = parseInt(i, 10); // don't forget the second param
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        time = hours+' hours '+minutes+' minutes ';
        return time;
    }

    var address, bounds, center, dest, dest_lat, dest_lng, directionsService, estimate_dest, estimate_origin, geocoder, map, mapOptions, none_location, one_location, origin, origin_lat, origin_lng, renderDirections, requestDirections, table, zoom, route, distance, distance1, duration, current, current_lng, current_lat, waypnt, estimate_current, directionsRenderer;
    table = $("#gmap");
    waypnt = [];
    dest_lng = table.attr("dest_lat");
    dest_lat = table.attr("dest_lng");
    origin_lng = table.attr("origin_lat");
    origin_lat = table.attr("origin_lng");
    dest = table.attr("dest");
    current_lng = table.attr("current_lng");
    current_lat = table.attr("current_lat");

    var current1 = table.attr("current");
    var origin1 = table.attr("origin");

    if (current1 === ''){
        origin = origin1;

    }
    else{
        origin = current1;
        var waypoint = origin1;
        estimate_current = new google.maps.LatLng(parseInt(current_lat), parseInt(current_lng));
    }
    estimate_origin = new google.maps.LatLng(parseInt(origin_lat), parseInt(origin_lng));
    estimate_dest = new google.maps.LatLng(parseInt(dest_lat), parseInt(dest_lng));
    geocoder = new google.maps.Geocoder();

    directionsService = new google.maps.DirectionsService;
    directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});


    renderDirections = function(result) {
        directionsRenderer.setMap(map);
        return directionsRenderer.setDirections(result);
    };
    var icons1 = {
        start: {
            name: 'Current Location',
            icon: '/assets/truck.png'
        },
        load: {
            name: 'Load Pickup',
            icon: '/assets/crate.png'
        },
        info: {
            name: 'Destination',
            icon: '/assets/enduser.png'
        }
    };
    var icons = {
        start: new google.maps.MarkerImage(
            // URL
            '/assets/truck.png',
            // (width,height)
            new google.maps.Size( 32, 32 ),
            // The origin point (x,y)
            new google.maps.Point( 0, 0 ),
            // The anchor point (x,y)
            new google.maps.Point( 13, 32 )
        ),
        load: new google.maps.MarkerImage(
            // URL
            '/assets/crate.png',
            // (width,height)
            new google.maps.Size( 32, 32 ),
            // The origin point (x,y)
            new google.maps.Point( 0, 0 ),
            // The anchor point (x,y)
            new google.maps.Point( 13, 32 )
        ),
        end: new google.maps.MarkerImage(
            // URL
            '/assets/enduser.png',
            // (width,height)
            new google.maps.Size( 32, 32 ),
            // The origin point (x,y)
            new google.maps.Point( 0, 0 ),
            // The anchor point (x,y)
            new google.maps.Point( 13, 32 )
        )
    };
    function makeMarker( position, icon, title ) {
        new google.maps.Marker({
            position: position,
            map: map,
            icon: icon,
            title: title
        });
    }
    requestDirections = function(start, end, waypnt) {
        return directionsService.route({
            origin: start,
            destination: end,
            waypoints: waypnt,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function(result) {
            myObj = result;
            route = result.routes[0];
            distance = document.getElementById('distance');
            distance1 = document.getElementById('distance1');
            var distance2 = document.getElementById('distance2');
            duration = document.getElementById('duration');
            var total_distance = 0;
            var total_duration = 0;

            for (var i = 0; i < route.legs.length; i++) {
                if (route.legs.length > 1){
                    if (i === 0 ){
                        distance.innerHTML += ' <b>Dead Head:</b> <br>';
                        makeMarker( route.legs[i].start_location, icons.start, "Current Location" );
                    }
                    else{
                        distance.innerHTML += ' <b>Load Route:</b> <br>';
                        distance2.innerHTML = Math.round(getMiles(route.legs[i].distance.value)) + " Miles"
                        makeMarker( route.legs[i].start_location, icons.load, "Origin" );
                        makeMarker( route.legs[i].end_location, icons.end, 'Destination' );
                    }
                }
                else{
                    distance.innerHTML += ' <b>Load Route:</b> <br>';
                    distance2.innerHTML = Math.round(getMiles(route.legs[i].distance.value)) + " Miles"
                    makeMarker( route.legs[i].start_location, icons.load, "Origin" );
                    makeMarker( route.legs[i].end_location, icons.end, 'Destination' );
                }


                distance.innerHTML += route.legs[i].start_address + '* to ';
                distance.innerHTML += route.legs[i].end_address + '*<br>';
                distance.innerHTML += route.legs[i].duration.text + '<br>';
                distance.innerHTML += route.legs[i].distance.text + '<br><br>';
                total_duration += route.legs[i].duration.value;
                total_distance += route.legs[i].distance.value;
            }
            distance.innerHTML += '<small>*Based On Estimated Origin & Destination Locations</small>';
            distance1.innerHTML = Math.round(getMiles(total_distance)) + " Miles";
            duration.innerHTML = toHHMMSS(total_duration);

            return renderDirections(result);
        });
    };



    one_location = false;
    none_location = false;
    if (dest.toLowerCase() === "anywhere" && origin.toLowerCase() === "anywhere") {
        center = new google.maps.LatLng(37.2153, -93.2981);
        one_location = true;
        none_location = true;
        zoom = 4;
    } else if (dest.toLowerCase() === "anywhere") {
        center = estimate_origin;
        address = origin;
        zoom = 6;
        one_location = true;
    } else if (origin.toLowerCase() === "anywhere") {
        center = estimate_dest;
        address = dest;
        zoom = 6;
        one_location = true;
    } else {
        center = new google.maps.LatLng(34, 34);
        zoom = 6;
    }
    mapOptions = {
        center: center,
        zoom: zoom,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    if (one_location) {
        if (!none_location) {
            return geocoder.geocode({
                'address': address
            }, function(results, status) {
                var marker;
                return marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: 'Loadmax'
                });
            });
        }
    } else {
        bounds = new google.maps.LatLngBounds();
        if (estimate_current){
            bounds.extend(estimate_current);
        }
        bounds.extend(estimate_origin);
        bounds.extend(estimate_dest);
        map.fitBounds(bounds);
        var legend = document.getElementById('legend');
        for (var key in icons1) {
            var type = icons1[key];
            var name = type.name;
            var icon = type.icon;
            var div = document.createElement('div');
            div.innerHTML = '<img src="' + icon + '"> ' + name;
            legend.appendChild(div);
        }
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
        if (waypoint){
            waypnt.push({
                location:waypoint,
                stopover:true});
        }
        return requestDirections(origin, dest, waypnt);

    }

};

here is my code for the html view:

<div class="span6" id="map_canvas" style="height:400px"></div>

and i initiate the maps by this:

initialize_map();

By the way everything you see in those pictures are generated thru an ajax request that is replacing everything in that div with this command:

$("#map_info_div").replaceWith(
        "<%= escape_javascript(render :partial => 'classic_dialogs/load_search/load_details', :locals => {:load_info => @load_info, :current1 => @current}) %>"
);

so every time that whole section is completely redrawn and calls a new:

initialize_map();

UPDATE:

i have tried to use this:

google.maps.event.trigger(map_canvas,'resize');

It will give me back the rest of the map but it is still not in the Bounds that should be set.

I currently have the rendering process in a function that i call when the html is loaded.

I have been trying to access the map instance from the console of chrome browser but since the map variable is in the function i am unable to access it

This map is being displayed in a JQUERY DIALOG Box if that has any effect

From working with this it is like the google map canvas is rendering from point 0,0 of the dialog box because every time i use the re-size code i have to drag the canvas down and to the right to see the points...

like image 342
Big Al Ruby Newbie Avatar asked May 13 '15 14:05

Big Al Ruby Newbie


People also ask

How are Google maps rendered?

As described in the previous section, the Maps API uses a combination of DIV and IMG elements to render the map. Each image is placed within a parent container and that container is moved as the map pans.

What is the daily limit for Google Maps API?

While there is no maximum number of requests per day, the following usage limits are in place for the Maps JavaScript API: 30,000 requests per minute. 300 requests per minute per IP address. In the Google Cloud Console, this quota is referred to as Map loads per minute per user.


1 Answers

I have SOLVED this issue... Since the map was in a dialog box it was tring to render the map before it was finished loading the HTML so i had to put an open fuction on the dialog box to trigger it after the html was loaded

$("#map_form").dialog({
    open: function( event, ui ) {
        initialize_map();
    },
    autoOpen: false,
    width: 1000,
    buttons: {
        "Close": function () {
            $(this).dialog("close");
        }
    }
});

Hope this helps others

like image 149
Big Al Ruby Newbie Avatar answered Oct 16 '22 04:10

Big Al Ruby Newbie