Link to home
Start Free TrialLog in
Avatar of danfiggolf
danfiggolf

asked on

Google Map Share Location and Directions Appear Twice

Looking at the code you will see  google.maps.LatLng is used once, but visiting the test page of http://legendsnorcal.dfigdesign.com/maps/menutest2a.html you will experience twice the dialog asking if you would like to share your location.  As well, the directions will result a second time right underneath the first - so it's duplicating the directions on the same page.

Do you see why this is happening when google.maps.LatLng is used only once in the code?
<!doctype html>
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3" type="text/javascript"></script>
        <script type="text/javascript">
$(document).on('pageinit', '#page1', function(){
    
    $('form').submit(function(){
       
        latlong = $('[name=latlong]').val();
                
        $.mobile.changePage('#page2');
        return false;        
    });
    
});
$(document).on('pageinit', '#page2', function(){
	            var map,
                currentPosition,
                directionsDisplay, 
                directionsService,
				selectedDest = $('[name=latlong]').val();
  });
</script>
 <script type="text/javascript">
		
            $('.page-map1').live("pageshow", "#map_page", function() {alert("page-map1, pageshow");
                initialize();
            });
 
            $('.page-map1').live("pagecreate", "#map_page", function() {alert("page-map1, pagecreate");
                $('#submit').click(function() {
                    calculateRoute();
                    return false;
                });
            });
			
            var directionsDisplay; 
            var directionsService = new google.maps.DirectionsService();

            function initializeMapAndCalculateRoute(lat, lon)
			{
			    directionsDisplay = new google.maps.DirectionsRenderer();                
                currentPosition = new google.maps.LatLng(lat, lon);

                map = new google.maps.Map(document.getElementById('map_canvas'), {
                   zoom: 15,
                   center: currentPosition,
                   mapTypeId: google.maps.MapTypeId.ROADMAP
                 });

                directionsDisplay.setMap(map);

                 var currentPositionMarker = new google.maps.Marker({
                    position: currentPosition,
                    map: map,
                    title: "Current position"
                });

                // current position marker info
                /*
                var infowindow = new google.maps.InfoWindow();
                google.maps.event.addListener(currentPositionMarker, 'click', function() {
                    infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
                    infowindow.open(map, currentPositionMarker);
                });
                */

                // calculate Route
                calculateRoute();
            }

            function locError(error) {
               // the current position could not be located
            }

            function locSuccess(position) {
                // initialize map with current position and calculate the route
                initializeMapAndCalculateRoute(position.coords.latitude, position.coords.longitude);
            }

            function calculateRoute() {
				var targetDestination = $('#latlong').val();
				var coords = targetDestination.split(",");
                targetDestination =  new google.maps.LatLng(parseInt(coords[0]),parseInt(coords[1]));
                if (currentPosition != '' && targetDestination != '') {

                    var request = {
                        origin: currentPosition, 
                        destination: targetDestination,
                        travelMode: google.maps.DirectionsTravelMode["DRIVING"]
                    };
                    directionsService.route(request, function(response, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            directionsDisplay.setPanel(document.getElementById("directions"));
                            directionsDisplay.setDirections(response); 
                            /*
                                var myRoute = response.routes[0].legs[0];
                                for (var i = 0; i < myRoute.steps.length; i++) {
                                    alert(myRoute.steps[i].instructions);
                                }
                            */
                            $("#results").show();
                        }
                        else {
                            $("#results").hide();
                        }
                    });
                }
                else {
                    $("#results").hide();
                }
            }

            $(document).live("pagebeforeshow", "#map_page", function() {
                // find current position and on success initialize map and calculate the route
                navigator.geolocation.getCurrentPosition(locSuccess, locError);
            });

        </script>
</head>

<body>
<div data-role="page" id="page1">

    <div data-role="header">
        <h1>Legend Restaurant Locations</h1>
    </div><!-- /header -->

    <div data-role="content">    
       
        <form>
<label class="select ui-select" for="latlong">Choose a Legends Restaurant:</label>
<div class="ui-select">
<div class="ui-btn ui-shadow ui-btn-corner-all ui-btn-icon-right ui-btn-up-c" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="arrow-d" data-iconpos="right" data-theme="c">
<select id="latlong" name="latlong">
<option value="38.770551,-121.294578">Bennett Valley</option>
		<option value="38.772345,-122.295678">Diamond Oaks</option>
		<option value="38.774567,-123.296789">Diablo Creek</option>
		<option value="38.778910,-124.297890">Paradise Valley</option>
</select>

            <input type="submit" value="Submit" />    
</div>
</div>
<div class="ui-btn ui-shadow ui-btn-corner-all ui-submit ui-btn-up-c" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="" data-iconpos="" data-theme="c" aria-disabled="false"></div>
</form>           
    </div><!-- /content -->

</div>

     <div data-role="page" id="page2">
        <div data-role="header">
                <h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a></h1>
            </div>
            <div data-role="content">   
                <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
                    <div id="map_canvas" style="height:350px; width: 100%; margin: 0px; padding: 0px"></div>
                </div>
                <div id="results" style="display:none;">
                    <div id="directions"></div>
                </div>
            </div>
        <div data-role="footer">
            Copyright
        </div>
      </div>

</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of danfiggolf
danfiggolf

ASKER

Tommy - thank you.  I like how you move the following to the initialization of the second page, for it now eliminates asking to OK shared location twice:
$(document).on('pageinit', '#page2', function(){
		var selectedDest = $('[name=latlong]').val();
		navigator.geolocation.getCurrentPosition(locSuccess, locError);
});

Open in new window


The only problem is the directions are not at all relative to the lat-long coordinates delivered by the menu selection.  I'm trying to figure out where the lat-long values come from to result with non-related coordinates?  I think there must be a way to clear the memory of coordinates.

I took your code and placed it in a different page for testing - Tommy's Code
I'm trying to see why the resulting latlong everytime is 37.986272,-122.010576 when Firebug shows the correct coordinates  are populating in targetDestination -

From Firebug:
at the point of gmaptest.html#page2 line 75> targetDestination = new google.maps.LatLng(parseInt(coords[0]),parseInt(coords[1]));
      
coords- ["38.42036", "-122.662246"]
      
request- undefined
      
targetDestination- "38.42036,-122.662246"
I made some modifications to the version of your script I posted originally. Mainly to add some error reporting and changes to how and when variables are initiated. I also changed the parseInt to parseFloat to maintain the accuracy of the locations. Dumb mistake on my part to use parseInt. See if this works better for you.
<!doctype html>
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3" type="text/javascript"></script>
        <script type="text/javascript">
$(document).on('pageinit', '#page1', function(){
    
    $('form').submit(function(){
       
        latlong = $('[name=latlong]').val();
                
        $.mobile.changePage('#page2');
        return false;        
    });
    
});
$(document).on('pageinit', '#page2', function(){
		var selectedDest = $('[name=latlong]').val();
		navigator.geolocation.getCurrentPosition(locSuccess, locError);
});
</script>
 <script type="text/javascript">
			
            var currentPosition;

            function initializeMapAndCalculateRoute(lat, lon)
			{                
                currentPosition = new google.maps.LatLng(lat, lon);

                map = new google.maps.Map(document.getElementById('map_canvas'), {
                   zoom: 15,
                   center: currentPosition,
                   mapTypeId: google.maps.MapTypeId.ROADMAP
                 });

                
                 var currentPositionMarker = new google.maps.Marker({
                    position: currentPosition,
                    map: map,
                    title: "Current position"
                });

                // current position marker info
                /*
                var infowindow = new google.maps.InfoWindow();
                google.maps.event.addListener(currentPositionMarker, 'click', function() {
                    infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
                    infowindow.open(map, currentPositionMarker);
                });
                */
                // calculate Route
                calculateRoute();
            }

            function locError(error) {
               // the current position could not be located
			    switch(error.code)  
            	{  
                	case error.PERMISSION_DENIED: alert("user did not share geolocation data");  
                	break;  
                	case error.POSITION_UNAVAILABLE: alert("could not detect current position");  
                	break;  
                	case error.TIMEOUT: alert("retrieving position timed out");  
                	break;  
                	default: alert("unknown error");  
                	break;  
           	 	}  
            }

            function locSuccess(position) {
                // initialize map with current position and calculate the route
                initializeMapAndCalculateRoute(position.coords.latitude, position.coords.longitude);
            }

            function calculateRoute() {
		var targetDest = $('#latlong').val();
		var coords = targetDest.split(",");
                var targetDestination =  new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
                if (currentPosition != '' && targetDestination != '') {

                    var request = {
                        origin: currentPosition, 
                        destination: targetDestination,
                        travelMode: google.maps.DirectionsTravelMode["DRIVING"]
                    }; 
            		var directionsService = new google.maps.DirectionsService();
                    directionsService.route(request, function(response, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
			    var directionsDisplay = new google.maps.DirectionsRenderer();
			    directionsDisplay.setMap(map);
                            directionsDisplay.setPanel(document.getElementById("directions"));
                            directionsDisplay.setDirections(response); 
                            /*
                                var myRoute = response.routes[0].legs[0];
                                for (var i = 0; i < myRoute.steps.length; i++) {
                                    alert(myRoute.steps[i].instructions);
                                }
                            */			    			

                            $("#results").show();
                        }
                        else {
                            $("#results").hide();
							alert(status);
                        }
                    });
                }
                else {
                    $("#results").hide();
                }
            }

        </script>
</head>

<body>
<div data-role="page" id="page1">

    <div data-role="header">
        <h1>Legend Restaurant Locations</h1>
    </div><!-- /header -->

    <div data-role="content">    
       
        <form>
<label class="select ui-select" for="latlong">Choose a Legends Restaurant:</label>
<div class="ui-select">
<div class="ui-btn ui-shadow ui-btn-corner-all ui-btn-icon-right ui-btn-up-c" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="arrow-d" data-iconpos="right" data-theme="c">
<span class="ui-btn-inner ui-btn-corner-all">
<select id="latlong" name="latlong">
		<option value="38.42036,-122.662246">Bennett Valley</option>
		<option value="38.012494,-122.023577">Diablo Creek</option>
		<option value="38.752124,-121.288006">Diamond Oaks</option>
		<option value="38.29647,-122.024275">Paradise Valley</option>
        <option value="38.291475,-122.07136">Rancho Solano</option>
        <option value="38.776647,-121.332648">Woodcreek</option>
</select>

            <input type="submit" value="Submit" />    
</div>
</div>
<div class="ui-btn ui-shadow ui-btn-corner-all ui-submit ui-btn-up-c" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="" data-iconpos="" data-theme="c" aria-disabled="false"></div>
</form>           
    </div><!-- /content -->

</div>

     <div data-role="page" id="page2">
        <div data-role="header">
                <h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a></h1>
            </div>
            <div data-role="content">   
                <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
                    <div id="map_canvas" style="height:350px; width: 100%; margin: 0px; padding: 0px"></div>
                </div>
                <div id="results" style="display:none;">
                    <div id="directions"></div>
                </div>
            </div>
        <div data-role="footer">
            Copyright
        </div>
      </div>

</body>
</html>

Open in new window