Skip to content

Instantly share code, notes, and snippets.

@kinglozzer
Last active December 14, 2015 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kinglozzer/083664b9e23eeafcc6a2 to your computer and use it in GitHub Desktop.
Save kinglozzer/083664b9e23eeafcc6a2 to your computer and use it in GitHub Desktop.
Google Maps CMS Javascript
/**
* File: GMapsPage.js
*/
(function($) {
$.entwine('ss', function($) {
/**
* ID: #GMapsPage_Map
*
* Initialise map upon matching appropriate field
*/
$('#GMapsPage_Map').entwine({
// Constructor: onmatch
onmatch: function() {
initialiseMap();
}
});
/**
* ID: #Root_GoogleMap[aria-hidden="false"]
*
* Redraw map when tab is visible
*/
$('#Root_GoogleMap[aria-hidden="false"]').entwine({
// Constructor: onmatch
onmatch: function() {
google.maps.event.trigger(map, 'resize');
}
});
/**
* Class: .cms-edit-form input[name=SearchAddress]
*
* Bind events for geocoding address
*/
$('.cms-edit-form input[name=SearchAddress]').entwine({
// Constructor: onmatch
onmatch: function() {
var self = this;
this.bind('keypress blur', function(e) {
if (d) clearTimeout(d);
// Set timeout to prevent lots of requests
var d = setTimeout(function() {
geocodePosition(self.val());
}, 500);
});
}
});
});
var lat, // Coordinates
lng,
latField = $('.cms-edit-form input[name=GMapLat]'), // Fields
lngField = $('.cms-edit-form input[name=GMapLon]'),
center = new google.maps.LatLng(latField.val(), lngField.val()),
options = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('GMapsPage_Map'), options),
marker = new google.maps.Marker({
position: center,
map: map,
draggable: true
}),
geocoder = new google.maps.Geocoder();
function initialiseMap() {
center = marker.getPosition();
map.panTo(center);
google.maps.event.addListener(marker, 'dragend', updateMarkerPosition);
}
function updateMarkerPosition() {
var latLng = marker.getPosition();
latField.val(latLng.lat()).change();
lngField.val(latLng.lng()).change();
}
function geocodePosition(address) {
geocoder.geocode({
'address': address
}, function(responses) {
if (responses && responses.length > 0) {
lat = responses[0].geometry.location.lat();
lng = responses[0].geometry.location.lng();
center = new google.maps.LatLng(lat, lng);
latField.val(lat);
lngField.val(lng);
map.setCenter(center);
marker.setPosition(center);
updateMarkerPosition();
}
}
);
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment