blechreiz-website/location_field/media/form.js

128 lines
4.4 KiB
JavaScript

($ || django.jQuery)(function($){
function location_field_load( map, base_field, initZoom )
{
var parent = map.parent().parent();
var coordinate_field = parent.find('input[type=text]');
var map;
var current_position;
//coordinate_field.hide();
coordinate_field.attr("readonly","readonly")
function load()
{
var options = { mapTypeId: google.maps.MapTypeId.HYBRID };
map = new google.maps.Map(map[0], options);
if ( coordinate_field.val() ) // Already values in the coordinate field
{
var l = coordinate_field.val().split(/,/);
if (l.length > 1)
{
current_position = new google.maps.LatLng(l[0], l[1]);
map.setZoom( parseInt( l[2] ) );
}
}
if ( ! current_position )
{
var locationRohr = new google.maps.LatLng( 49.340174,10.890595 );
current_position = locationRohr;
map.setZoom( initZoom );
}
function savePosition( p ) {
current_position = p;
coordinate_field.val( current_position.lat().toFixed(6) + "," + current_position.lng().toFixed(6) + "," + map.getZoom() );
}
var marker = new google.maps.Marker({
map: map,
position: current_position,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(mouseEvent) {
savePosition(mouseEvent.latLng);
});
google.maps.event.addListener(map, 'click', function(mouseEvent){
marker.setPosition(mouseEvent.latLng);
savePosition( mouseEvent.latLng );
});
google.maps.event.addListener(map, 'zoom_changed', function(mouseEvent){
savePosition( current_position );
});
base_field.bindWithDelay( "keypress", function() {
geocode( base_field.val() , function(l){
coordinate_field.val( l.lat()+','+l.lng() );
});
onLocationCoordinateChange();
}, 2000 );
function onLocationCoordinateChange()
{
var latlng = jQuery(this).val().split(/,/);
if (latlng.length < 2) return;
var latlng = new google.maps.LatLng( latlng[0], latlng[1] );
placeMarker( latlng );
map.setZoom( latlng[2] );
}
function placeMarker(location) {
marker.setPosition(location);
map.setCenter(location);
savePosition(location);
map.panTo(location);
}
function geocode(address, cb) {
var result;
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({"address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
cb(results[0].geometry.location);
placeMarker(results[0].geometry.location);
}
});
}
}
/*
function geocode_reverse(location, cb) {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({"latLng": location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
cb(results[0].geometry.location);
placeMarker(results[0].geometry.location);
}
});
}
}*/
placeMarker( current_position );
}
load();
}
$('input[data-location-widget]').each(function(){
var $el = $(this);
var $map = $($el.attr('data-map')),
$based_field = $(($el.attr('data-based-field'))),
zoom = parseInt($el.attr('data-zoom'));
location_field_load( $map, $based_field, zoom );
});
});