Skip to content

Instantly share code, notes, and snippets.

@NickDeckerDevs
Created May 8, 2017 14:29
Show Gist options
  • Select an option

  • Save NickDeckerDevs/e05b7db4a1499436365d465bd0be22b9 to your computer and use it in GitHub Desktop.

Select an option

Save NickDeckerDevs/e05b7db4a1499436365d465bd0be22b9 to your computer and use it in GitHub Desktop.
Complete Cora Locations
<?php
/**
* Template Name: Locations
*/
// $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$locationQuery = 'All Clinics';
$locationsArray = [];
$clinic = false;
$searchValue = isset($_GET['location']) ? $_GET['location'] : '';
if(isset($_GET['location'])) {
$query = "SELECT * FROM dbo.CLINICS_DATA WHERE INCLUDEINSEARCH = 1;";
} elseif(!isset($_GET['type']) OR ( isset($_GET['type']) && $_GET['type'] == 'all' ) ) {
$query = "SELECT * FROM dbo.CLINICS_DATA WHERE INCLUDEINSEARCH = 1;";
} elseif (isset($_GET['type']) && $_GET['type'] == 'state') {
$state = $_GET['state'];
switch($state) {
case 'MI':
$stateNice = 'All Michigan';
break;
case 'NC':
$stateNice = 'All North Carolina';
break;
case 'SC':
$stateNice = 'All South Carolina';
break;
default:
$stateNice = 'All Florida';
}
$locationQuery = $stateNice . ' Clinics';
$query = "SELECT * FROM dbo.CLINICS_DATA WHERE STATE = '$state' AND INCLUDEINSEARCH = 1;";
} elseif (isset($_GET['type']) && $_GET['type'] == 'region') {
$region = str_replace('+', ' ', $_GET['region']);
$region = (strpos($region, '%26') > -1) ? str_replace('%26', '&', $region) : $region;
$locationQuery = $region . ' Clinics';
$query = "SELECT * FROM dbo.CLINICS_DATA WHERE (REGION_1 = '$region' OR REGION_2 = '$region' OR REGION_3 = '$region') AND INCLUDEINSEARCH = 1;";
} else {
$clinic = true;
$clinicId = $_GET['clinic'];
$query = "SELECT * FROM dbo.CLINICS_DATA WHERE CLINIC_ID = $clinicId";
}
$locationsArray = getClinicData($query);
$locationCount = 0;
$latitude = '';
$longitude = '';
function formatTelephone($phone_number) {
$cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
preg_match('/(\d{3})(\d{3})(\d{4})/', $cleaned, $matches);
return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
}
$mapArray = getLocations($locationsArray);
get_header();
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="wrap-content" class="wrap-content default-business-page location-page">
<div id="content" class="container">
<section>
<?php if(!$clinic) { ?>
<div class="row">
<div class="col-sm-12 locations-header">
<div class="col-sm-7">
<h1>Find A Clinic</h1>
<p class="h4">Convenient Locations - Quality Service</p>
<p>When calling on our clinics, you will appreciate our rapid-scheduling and commitment to same-day treatments.</p>
<p>Our treatment hours are flexible to accomodate our patients' busy schedules. Furthermore, our intake personnel are available to answer your questions and to promptly serve you.</p>
</div>
<div class="col-sm-5 text-center">
<form id="search-locations-form">
<input type="text" name="location" id="location" placeholder="Enter Street, Zip Code" value="<?php echo $searchValue; ?>"/>
<input type="submit" id="location-submit" value="FIND" />
</form>
</div>
</div>
</div>
<?php } ?>
<div class="row">
<div class="col-sm-12 locations-content">
<div class="col-sm-4 region-wrapper">
<h2>Browse Clinics: <span>LISTED ALPHABETICALLY</h2>
<div class="region col-sm-10">
<div class="region-content">
<?php getRegionsArray(); ?>
<?php getClinicRegionMenu(); ?>
</div>
<img src="<?php echo get_template_directory_uri() . '/images/locations-logo.png'; ?>">
</div>
</div>
<div class="col-sm-8 clinic-wrapper">
<?php if($clinic == false) { ?>
<h2>Clinic Locations: <span><?php echo $locationQuery; ?></span></h2>
<div id="map" style="height: 650px; width: 100%;"></div>
<?php } else {
$clinic = $locationsArray[0];
$mapAddress = $clinic['STREET'].'<br>'.$clinic['CITY'].', '.$clinic['STATE'].' '.$clinic['ZIP'];
$googleAddress = str_replace('<br>', '+', $mapAddress);
$googleAddress = str_replace(',', '', $googleAddress);
$googleAddress = str_replace(' ', '+', $googleAddress);
?>
<div class="col-md-12">
<h1>CORA <?php echo $clinic['LOCATION_ID']; ?></h1>
</div>
<div class="col-md-6">
<p><?php echo $clinic['STREET'].'<br>'.$clinic['CITY'].', '.$clinic['STATE'].' '.$clinic['ZIP']; ?></p>
<p><a href="https://www.google.com/maps?saddr&daddr=<?php echo $googleAddress; ?>" target="_blank">Get Directions</a></p>
<p>Phone: <?php echo '<a href="tel:'.$clinic['PHONE'].'">'.formatTelephone($clinic['PHONE']).'</a><br>'; ?>
Fax: <?php echo formatTelephone($clinic['FAX']); ?></p>
<p><?php echo $clinic['DESCRIPTION']; ?></p>
<h3>Services Offered:</h3>
<?php echo servicesOffered($clinic); ?>
</div>
<div class="col-md-6">
<div class="col-md-12">
<img src="/wp-content/themes/cora/images/clinics/<?php echo substr($clinic['IMAGE_URL_MEDIUM'], strrpos($clinic['IMAGE_URL_MEDIUM'], '/') + 1); ?>"/>
<?php echo clincHours($clinic); ?>
<h5>Request Appointment</h5>
<p>Request an appointment with this clinic location.</p>
<p><a href="/appointment?clinic=<?php echo $clinic['CLINIC_ID']; ?>">Make A Request Now</a></p>
<h5>Referrals:</h5>
<p>Refer a patient using the RapidReferral service.</p>
<p><a href="/referral">Make a Referral Now</a></p>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<?php the_content(); ?>
</div>
</section>
</div>
</div>
<script>
jQuery(document).ready(function($) {
$('.region .state').on('click', function() {
var region = $(this);
region.next().slideToggle();
});
$('#search-locations-form').on('submit', function() {
getLocation();
})
$('#map').on('click', '.street-addr', function() {
$(this).attr('value', '');
});
$('#map').on('click', '.zoom-to-location', function() {
var index = $(this).data('index');
zoomLocation(index);
});
$('.region li').on('click', function() {
var newUrl = window.location.href;
var type = $(this).data('type');
newUrl = removeURLParameter(newUrl, 'location');
newUrl = removeURLParameter(newUrl, 'lat');
newUrl = removeURLParameter(newUrl, 'lng');
newUrl = updateQueryParam(newUrl, 'type', type);
switch(type) {
case 'region':
newUrl = updateQueryParam(newUrl, 'region', cleanQueryValue($(this).data('region')));
newUrl = updateQueryParam(newUrl, 'state', '');
newUrl = updateQueryParam(newUrl, 'clinic', '');
break;
case 'state':
newUrl = updateQueryParam(newUrl, 'state', cleanQueryValue($(this).data('state')));
newUrl = updateQueryParam(newUrl, 'region', '');
newUrl = updateQueryParam(newUrl, 'clinic', '');
break;
default:
newUrl = updateQueryParam(newUrl, 'region', '');
newUrl = updateQueryParam(newUrl, 'state', '');
newUrl = updateQueryParam(newUrl, 'clinic', '');
}
window.location.href = newUrl;
});
$('#map').on('click', '.clinic', function() {
var newUrl = window.location.href;
var clinic = $(this).data('clinic')
newUrl = removeURLParameter(newUrl, 'location');
newUrl = removeURLParameter(newUrl, 'lat');
newUrl = removeURLParameter(newUrl, 'lng');
newUrl = updateQueryParam(newUrl, 'type', 'clinic');
newUrl = updateQueryParam(newUrl, 'region', '');
newUrl = updateQueryParam(newUrl, 'state', '');
newUrl = updateQueryParam(newUrl, 'clinic', clinic);
window.location.href = newUrl;
});
function updateQueryParam(uri, key, value) {
var regEx = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if(uri.match(regEx)) {
return uri.replace(regEx, '$1' + key + "=" + value + '$2');
} else {
return uri + separator + key + "=" + value;
}
}
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
return url;
} else {
return url;
}
}
function cleanQueryValue(str) {
str = str.split('&').join('%26');
return str.split(' ').join('+');
}
});
</script>
<script>
var search = false;
var oLat = parseInt(35);
var oLong = parseInt(-81);
var zoomOn = false;
var defaultZoom = 5;
var url = window.location.href;
if(url.indexOf('location=') > -1) {
search = true;
var params = getJsonFromUrl();
oLat = parseInt(params.lat);
oLong = parseInt(params.lng);
zoomOn = true;
defaultZoom = 2;
}
var locations = <?php echo json_encode($mapArray); ?>;
var map;
var markers = new Object();
var infowindow = new Object();
var bounds = new Object();
function getJsonFromUrl() {
var query = location.search.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
function formatPhone(phone) {
if(isNaN(phone)) return phone;
if(phone.length < 10) return phone;
return phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)
}
function fixImage(imageUri) {
var imageName = imageUri.substring(imageUri.lastIndexOf('/') + 1, imageUri.length);
return '/wp-content/themes/cora/images/clinics/' + imageName;
}
function getMarkerContent(index){
var location = locations[index];
var zoomText = zoomOn ? 'Zoom Out' : 'Zoom In';
var mapAddress = location.street+', '+ location.city+', '+ location.state + ' ' + location.zip;
var content = '<div class="marker-info">';
if(location.img) {
content += '<img src="' + fixImage(location.img) + '">';
}
content += '<p><strong><span class="clinic" data-clinic=' + location.id + '>' + location.name + '</span></strong>';
content += '<br>' + location.street + '<br>' + location.city + ', ' + location.state + ' ' + location.zip;
content += '<br>' + 'Phone: <a href="tel: ' + location.phone + '">' + formatPhone(location.phone) + '</a><br>';
content += '<br>' + 'Fax: ' + formatPhone(location.fax) + '<br>';
content += '<a class="zoom-to-location" data-index="' + index + '">'+zoomText+'</a></p>';
content += '<a href="/book-appointment?clinic=' + location.id + '" class="appointment" data-clinic="' + location.id + '">Request Appointment</a></p>';
content += '<form target="_blank" method="get" action="http://maps.google.com/maps">';
content += '<span class="title-descriptor">Start address:</span><br><input type="text" class="street-addr" value="Street, City, State, Zip" name="saddr" maxlength="90">&nbsp;';
content += '<input type="submit" class="button-descriptor" value="Get Directions"><input type="hidden" value="'+ mapAddress + '" name="daddr"></form></div>';
content += '</div>';
return content;
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: defaultZoom,
center: {lat: oLat, lng: oLong},
mapTypeId: 'roadmap'
});
infowindow = new google.maps.InfoWindow();
bounds = new google.maps.LatLngBounds();
var marker;
var counter = 0;
for(var i = 0; i < locations.length; i++) {
// getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2)
var distance = getDistanceFromLatLonInKm(
parseInt(locations[i].lat),
parseInt(locations[i].long),
parseInt(oLat),
parseInt(oLong)
);
if(distance < 150 || search == false) {
counter++;
marker = new google.maps.Marker({
infoIndex: i,
position: new google.maps.LatLng(locations[i].lat, locations[i].long),
map: map,
title: locations[i].name
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(getMarkerContent(i));
infowindow.open(map, marker);
}
})(marker, i));
}
}
if(counter < 1) {
jQuery('.clinic-wrapper').fadeOut();
alert('There was a low amount of search results. Try using the sidebar at the left to find a location near you.');
} else {
map.fitBounds(bounds);
}
}
function zoomLocation(index){
zoomOn = !zoomOn;
var zoomNow = defaultZoom;
var latlng = new google.maps.LatLng(oLat, oLong);
if(zoomOn) {
latlng = new google.maps.LatLng(locations[index].lat, locations[index].long);
zoomNow = map.getZoom() + 4;
}
map.setCenter(latlng);
map.setZoom(zoomNow);
infowindow.close();
infowindow.setContent(getMarkerContent(index));
infowindow.open(map, markers[index]);
}
function getLocation() {
var lat = '';
var lng = '';
var address = jQuery('#location').val();
var location = '';
var locArray = [];
if(address != '') {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
oLat = lat;
oLong = lng;
window.location.href= '/locations?location='+address+'&lat='+lat+'&lng='+lng;
} else {
console.log('error on address encode - google maps api');
alert('Please try again.');
}
});
}
}
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCWWxfxWzcX7qJaWTkBAgNOyjsUwCj5_Xc&callback=initMap">
</script>
<?php endwhile; endif;
get_footer('business-pages'); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment