Skip to content

Commit

Permalink
Populate JSON file
Browse files Browse the repository at this point in the history
  • Loading branch information
jsirish committed Sep 13, 2024
1 parent 85a0c00 commit 17b517b
Show file tree
Hide file tree
Showing 7 changed files with 138 additions and 91 deletions.
6 changes: 5 additions & 1 deletion _config/config.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Dynamic\Locations\Model\Location:
extensions:
- Dynamic\Elements\Locations\Extension\LocationDataExtension

Dynamic\Locations\Model\LocationCategory:
extensions:
- Dynamic\Elements\Locaitons\Extension\LocationCategoryDataExtension
- Dynamic\Elements\Locations\Extension\LocationCategoryDataExtension
101 changes: 59 additions & 42 deletions dist/js/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,24 +111,33 @@ const mapStyle = [{
function initMap() {
// Create the map.
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 52.632469, lng: -1.689423},
zoom: 7, // Initial zoom, this will change based on locations
center: {lat: 52.632469, lng: -1.689423}, // Initial center, this will also change
styles: mapStyle,
});

// Create a LatLngBounds object to calculate the map's bounds
const bounds = new google.maps.LatLngBounds();

// Load the stores GeoJSON onto the map.
map.data.loadGeoJson('$link', {idPropertyName: 'storeid'});
map.data.loadGeoJson('$link', {idPropertyName: 'storeid'}, function(features) {
// Once the GeoJSON is loaded, iterate over each feature
features.forEach(function(feature) {
// Get the feature's geometry (its location)
const geometry = feature.getGeometry();

// Define the custom marker icons, using the store's "category".
// map.data.setStyle((feature) => {
// return {
// icon: {
// url: `img/icon_${feature.getProperty('category')}.png`,
// scaledSize: new google.maps.Size(64, 64),
// },
// };
// });
// If the geometry is a point, extend the bounds to include this point
if (geometry.getType() === 'Point') {
const coordinates = geometry.get();
bounds.extend(coordinates); // Extend the bounds to include this location
}
});

// Fit the map's viewport to the bounds of the locations
map.fitBounds(bounds);
});

// Define the custom marker icons, using the store's "category".
const apiKey = '$key';
const infoWindow = new google.maps.InfoWindow();

Expand All @@ -137,9 +146,10 @@ const mapStyle = [{
const category = event.feature.getProperty('category');
const name = event.feature.getProperty('name');
const description = event.feature.getProperty('description');
const hours = event.feature.getProperty('hours');
const phone = event.feature.getProperty('phone');
const hours = event.feature.getProperty('hours') || 'Hours not available';
const phone = event.feature.getProperty('phone') || 'Phone not available';
const position = event.feature.getGeometry().get();

const content = sanitizeHTML`
<img style="float:left; width:200px; margin-top:30px" src="img/logo_${category}.png">
<div style="margin-left:220px; margin-bottom:20px;">
Expand All @@ -163,7 +173,7 @@ const mapStyle = [{
const input = document.createElement('input');
const options = {
types: ['address'],
componentRestrictions: {country: 'gb'},
// componentRestrictions: {country: 'gb'},
};

card.setAttribute('id', 'pac-card');
Expand Down Expand Up @@ -248,36 +258,43 @@ const mapStyle = [{
// The returned list will be in the same order as the destinations list
const service = new google.maps.DistanceMatrixService();
const getDistanceMatrix =
(service, parameters) => new Promise((resolve, reject) => {
service.getDistanceMatrix(parameters, (response, status) => {
if (status != google.maps.DistanceMatrixStatus.OK) {
reject(response);
(service, parameters) => new Promise((resolve, reject) => {
service.getDistanceMatrix(parameters, (response, status) => {
if (status != google.maps.DistanceMatrixStatus.OK) {
reject(response);
} else {
const distances = [];
const results = response.rows[0].elements;

for (let j = 0; j < results.length; j++) {
const element = results[j];

// Check if distance is available before accessing it
if (element.distance) {
const distanceText = element.distance.text;
const distanceVal = element.distance.value;
const distanceObject = {
storeid: stores[j],
distanceText: distanceText,
distanceVal: distanceVal,
};
distances.push(distanceObject);
} else {
const distances = [];
const results = response.rows[0].elements;
for (let j = 0; j < results.length; j++) {
const element = results[j];
const distanceText = element.distance.text;
const distanceVal = element.distance.value;
const distanceObject = {
storeid: stores[j],
distanceText: distanceText,
distanceVal: distanceVal,
};
distances.push(distanceObject);
}

resolve(distances);
console.log(`Distance not available for store ${stores[j]}`);
}
});
});

const distancesList = await getDistanceMatrix(service, {
origins: [origin],
destinations: destinations,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
}

resolve(distances);
}
});
});

const distancesList = await getDistanceMatrix(service, {
origins: [origin],
destinations: destinations,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.$MeasurementUnit,
});

distancesList.sort((first, second) => {
return first.distanceVal - second.distanceVal;
Expand Down
55 changes: 9 additions & 46 deletions src/Control/ElementLocationsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class ElementLocationsController extends ElementController
'json',
];

/**
* @config
*/
protected function init()
{
parent::init();
Expand Down Expand Up @@ -60,10 +63,10 @@ public function json()
{
$this->getResponse()->addHeader("Content-Type", "application/json");
$data = new ArrayData([
//"Locations" => $this->getLocations(),
"Locations" => $this->getLocations(),
]);

return $data->renderWith('Dynamic/Elements/Locations/Data/geoJSON');
return $data->renderWith('Dynamic/Elements/Locations/Data/JSON');
}

/**
Expand All @@ -80,41 +83,18 @@ public function getKey()
public function getLocations()
{
if (!$this->locations) {
$this->setLocations($this->request);
$this->setLocations();
}

return $this->locations;
}

/**
* @param HTTPRequest|null $request
*
* @return $this
*/
public function setLocations(HTTPRequest $request = null)
public function setLocations()
{

if ($request === null) {
$request = $this->request;
}

if ($this->Categories()->exists()) {
foreach ($this->Categories() as $category) {
$filter['Categories.ID'][] = $category->ID;
}
}

$this->extend('updateLocatorFilter', $filter, $request);

$filterAny = $this->config()->get('base_filter_any');
$this->extend('updateLocatorFilterAny', $filterAny, $request);

$exclude = $this->config()->get('base_exclude');
$this->extend('updateLocatorExclude', $exclude, $request);

$class = $this->data()->ClassName;
$locations = $class::get_locations($filter, $filterAny, $exclude);
$locations = DataToArrayListHelper::to_array_list($locations);
$locations = $this->data()->getLocationsList();

//allow for adjusting list post possible distance calculation
$this->extend('updateLocationList', $locations);
Expand All @@ -123,24 +103,6 @@ public function setLocations(HTTPRequest $request = null)
$locations = $locations->sort('Distance');
}

if ($this->getShowRadius()) {
$radiusVar = $this->data()->config()->get('radius_var');

if ($radius = (int)$request->getVar($radiusVar)) {
$locations = $locations->filterByCallback(function ($location) use (&$radius) {
return $location->Distance <= $radius;
});
}
}

//allow for returning list to be set as
$this->extend('updateListType', $locations);

$limit = $this->getLimit();
if ($limit > 0) {
$locations = $locations->limit($limit);
}

$this->locations = $locations;

return $this;
Expand All @@ -167,4 +129,5 @@ public function Link($action = null): string

return $segment;
}

}
3 changes: 2 additions & 1 deletion src/Element/ElementLocations.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
/**
* Class \Dynamic\Elements\Locations\Elements\ElementLocations
*
* @property string $MeasurementUnit
* @method ManyManyList|LocationCategory[] Categories()
*/
class ElementLocations extends BaseElement
Expand Down Expand Up @@ -44,7 +45,7 @@ class ElementLocations extends BaseElement
* @config
*/
private static array $db = [

'MeasurementUnit' => 'Enum("IMPERIAL, METRIC", "IMPERIAL")',
];

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Extension/LocationCategoryDataExtension.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

namespace Dynamic\Elements\Locaitons\Extension;
namespace Dynamic\Elements\Locations\Extension;

use Dynamic\Elements\Locations\Elements\ElementLocations;
use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\DataExtension;

/**
Expand Down
34 changes: 34 additions & 0 deletions src/Extension/LocationDataExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Dynamic\Elements\Locations\Extension;

use SilverStripe\ORM\DataExtension;
use SilverStripe\Forms\FieldList;

/**
* Class \Dynamic\Elements\Locations\Extension\LocationDataExtension
*
* @property Location|LocationDataExtension $owner
* @property string $Hours
*/
class LocationDataExtension extends DataExtension
{
/**
* @var array
* @config
*/
private static array $db = [
'Hours' => 'Text',
];

/**
* @param FieldList $fields
*/
public function updateCMSFields(FieldList $fields): void
{
$fields->insertAfter(
'Links',
$fields->dataFieldByName('Hours')
);
}
}
27 changes: 27 additions & 0 deletions templates/Dynamic/Elements/Locations/Data/JSON.ss
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"type": "FeatureCollection",
"features": [
<% loop $Locations %>
{
"geometry": {
"type": "Point",
"coordinates": [
$Lng,
$Lat
]
},
"type": "Feature",
"properties": {
<% if $Categories %>"category": "$Categories.First.Title.XML",<% end_if %>
<% if $Hours %>"hours": "10am - 6pm",<% end_if %>
<% if $Content %>"description": "$Content.XML",<% end_if %>
<% if $Title %>"name": "$Title.XML",<% end_if %>
<% if $PhoneNumbers %>"phone": "$Phonenumbers.First.Phone.XML",<% end_if %>
<% if $EmailAddresses %>"email": "$EmailAddresses.First.Email.XML",<% end_if %>
<% if $WebsiteLinks %>"website": "$WebsiteLinks.First.URL.XML",<% end_if %>
"storeid": "$ID.XML"
}
}<% if not $IsLast %>,<% end_if %>
<% end_loop %>
]
}

0 comments on commit 17b517b

Please sign in to comment.