jcadima
4/25/2017 - 8:56 PM

Google Directions from Multiple Markers

Google Directions from Multiple Markers



<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCimA1WCJnOViSudKzmrOUa3mua4aK7Dts"></script>
        
<!-- =================================THE CSS   ====================================== -->
<style>

#map_wrapper {
    height: 480px;
}

#map_canvas {
    width: 100%;
    height: 100%;
    overflow: visible !important;
}


.expand_directions {
    max-width: 1000px;
    margin: 10px auto 0 auto;
    overflow: hidden;
}
</style>


<!-- ================================= THE HTML   ====================================== -->
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>

<div class="clear"></div>

<div id="directionsPanel" style="display:none;"></div>

<div id="hide_map" style="display:none;">
<input class="btn btn-default" type="button" onClick="hideMap();" value="Close Map Directions">
</div>




<!-- ================================= THE JS   ====================================== -->
<script>

jQuery( document ).ready(function() {
	
<?php
	
$latitudes  = array();	
$longitudes = array() ;
$output     = array() ;
$addresses  = array();
$labels     = array(); 

 // Get lat and long by address         
$addresses[] = get_field('hialeah') ;  // get  address from custom field 
$addresses[] = get_field('medley') ;
$addresses[] = get_field('miami') ;
$addresses[] = get_field('west_palm_beach');

// Get Map Labels
$labels[] = get_field('location_1_label');
$labels[] = get_field('location_2_label');
$labels[] = get_field('location_3_label');
$labels[] = get_field('location_4_label');

for ( $i = 0 ; $i < 4 ; $i++ )  { 

	$prepAddr     = str_replace(' ','+',$addresses[$i]);
	$geocode      = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr . '&sensor=false');
	$output[]     = json_decode($geocode);
	$latitudes[]  = $output[$i]->results[0]->geometry->location->lat;
	$longitudes[] = $output[$i]->results[0]->geometry->location->lng;

}

?>  	
	

    var map;
    //Create LatLngBounds object.
    var bounds = new google.maps.LatLngBounds();
    
    var mapOptions = {
        mapTypeId: 'roadmap',
        scrollwheel: false,
        zoom: 5,
        styles: [{"stylers":[{"hue":"#ff1a00"},{"invert_lightness":true},{"saturation":-100},{"lightness":33},{"gamma":0.5}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#2D333C"}]}],
    };
                    
    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);
        
    // Multiple Markers
    var markers = [
        ['Location 1',  <?php echo $latitudes[0] ; ?> , <?php echo $longitudes[0] ; ?> ],
        ['Location 2',  <?php echo $latitudes[1] ; ?> , <?php echo $longitudes[1] ; ?> ],
        ['Location 3',  <?php echo $latitudes[2] ; ?> , <?php echo $longitudes[2] ; ?> ],
        ['Location 4',  <?php echo $latitudes[3] ; ?> , <?php echo $longitudes[3] ; ?> ]
    ];


   
                        
    // Info Window Content
    var infoWindowContent = [
        ['<div class="info_content">' + '<strong><?php echo $labels[0] ; ?></strong>' + '<p><?php echo $addresses[0] ; ?></p>' +  '<p>Get Directions:<br><input id="clientAddress" type="text"><input class="btn btn-primary dir_btn" type="button" onClick="getDir(<?php echo $latitudes[0]; ?>, <?php echo $longitudes[0] ; ?> )" value="Search"></p> '  +'</div>'],
        ['<div class="info_content">' + '<strong><?php echo $labels[1] ; ?></strong>' + '<p><?php echo $addresses[1] ; ?></p>' +  '<p>Get Directions:<br><input id="clientAddress" type="text"><input class="btn btn-primary dir_btn" type="button" onClick="getDir(<?php echo $latitudes[1]; ?>, <?php echo $longitudes[1] ; ?> )" value="Search"></p> '  +'</div>'],
        ['<div class="info_content">' + '<strong><?php echo $labels[2] ;  ?></strong>' + '<p><?php echo $addresses[2] ; ?></p>' +  '<p>Get Directions:<br><input id="clientAddress" type="text"><input class="btn btn-primary dir_btn" type="button" onClick="getDir(<?php echo $latitudes[2]; ?>, <?php echo $longitudes[2] ; ?> )" value="Search"></p> '  +'</div>'],
        ['<div class="info_content">' + '<strong><?php echo $labels[3] ; ?></strong>' + '<p><?php echo $addresses[3] ; ?></p>' +  '<p>Get Directions:<br><input id="clientAddress" type="text"><input class="btn btn-primary dir_btn" type="button" onClick="getDir(<?php echo $latitudes[3]; ?>, <?php echo $longitudes[3] ; ?> )" value="Search"></p> '  +'</div>']
        
    ];
    
    
        
    // Display multiple markers on a map
    var marker, i;
    var infoWindow = new google.maps.InfoWindow();
    
    
    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < markers.length; i++ ) {
        var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][0],
            icon: 'http://popbetaserver.com/projects/tropicfleet/wp-content/uploads/logomarker3.png'
            //icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
        });
        
        // Allow each marker to have an info window,
        // add click event listener for our markers   
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);

    }
    
    // Print Directions 
    geocoder = new google.maps.Geocoder();
    directionsService = new google.maps.DirectionsService();
    
    directionsDisplay = new google.maps.DirectionsRenderer({
        suppressMarkers: false
    });
    
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel") );
    

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(8);
        google.maps.event.removeListener(boundsListener);
    });
    
    
    

});

</script>


<script>
	
	
function getDir( latitude, longitude) {
	jQuery('#directionsPanel').addClass('expand_directions').show(2500) ;
	jQuery('#hide_map').show() ;
	// clientAddress is the address inside the map markers
    geocoder.geocode({
        'address': document.getElementById('clientAddress').value
    },

    function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var origin = results[0].geometry.location;
            var destination = new google.maps.LatLng( latitude, longitude );

            var request = {
                origin: origin,
                destination: destination,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });

        } else {
            document.getElementById('clientAddress').value =
                "Directions cannot be computed at this time.";
        }
    });
}	
	

function hideMap() {
	jQuery('#directionsPanel').hide() ;
	jQuery('#hide_map').hide() ;
}	
	
    
</script>