Настройка: У меня есть карта с одним маркером и набором полей ввода.Карта / init fn запускается при загрузке окна.
Что работает : обратное геокодирование: я перетаскиваю маркер и поле ввода (улица, номер, почтовый индекс, город, страна) обновляется с помощью функции mb_map.geocodePosition()
.
Задача: Теперь я хотел добавить нормальное геокодирование (Address> latLng), используя те же поля ввода, чтобы задать адрес и переместить маркер.Функция, которая вызывает нормальное геокодирование, запускается событием кнопки onClick="mb_map.encodeAddress()"
.
Проблема: По какой-то причине функция не получает аргументов, а console.log()
ничего не возвращает.Вместо этого страница перезагружается.Я написал комментарий в приведенном ниже коде, чтобы помочь вам легче найти часть, где он перестал работать.
<script type="text/javascript">
/**
* Global public map object & functions
* @since 0.1
*/
var mb_map = {
map: null,
marker: null,
geocoder: new google.maps.Geocoder(),
lat: null,
lng: null,
input:
{
street: document.getElementById( 'location_street' )
,nr: document.getElementById( 'location_nr' )
,zip: document.getElementById( 'location_zip' )
,city: document.getElementById( 'location_city' )
,country: document.getElementById( 'location_country' )
,lat: document.getElementById( 'location_lat' )
,lng: document.getElementById( 'location_lng' )
},
/**
* Reverse Geocoding
* lat/lng > Address
*
* @param pos
* @returns (object) | Geocoded address data
*/
geocodePosition: function( pos )
{
mb_map.geocoder.geocode(
{
latLng: pos
}
,function ( responses )
{
if ( responses && responses.length > 0 )
{
// THIS WORKS PERFECT
console.log( responses[0] );
mb_map.updateMarkerAddress( responses[0] );
}
else
{
mb_map.updateMarkerAddress( 'Cannot determine address at this location.' );
}
} );
},
/**
* Geocoding
* Address > lat/lng
*/
encodeAddress: function()
{
var address_formated =
mb_map.input.street.value
+ " "
+ mb_map.input.nr.value
+ ", "
+ mb_map.input.zip.value
+ ", "
+ mb_map.input.city.value
+ ", "
+ mb_map.input.country.value;
mb_map.geocoder.geocode(
{
// address: address_formated
// FOLLOWING LINE IS ONLY HERE, TO GET AN EASIER EXAMPLE
address: 'Lisbon, PT'
}
,function( responses, status )
{
// THIS IS WHERE NOTHING WORKS
console.log( responses );
if ( status == google.maps.GeocoderStatus.OK )
{
mb_map.map.setCenter( responses[0].geometry.location );
mb_map.updateMarkerAddress( responses[0].geometry.location );
mb_map.marker = new google.maps.Marker(
{
map: mb_map.map
,position: responses[0].geometry.location
} );
}
else
{
alert( "Geocode was not successful for the following reason: " + status );
}
} );
},
/**
* Update input fields on marker drop
*
* @param str
* @returns void
*/
updateMarkerAddress: function( str )
{
// not shown as not relevant
},
/**
* Setup map & marker
*
* @constructor
*/
init: function()
{
if ( navigator.geolocation )
{
navigator.geolocation.getCurrentPosition( function ( position )
{
mb_map.lat = position.coords.latitude;
mb_map.lng = position.coords.longitude;
var latLng = new google.maps.LatLng( mb_map.lat, mb_map.lng );
mb_map.map = new google.maps.Map( document.getElementById( 'map-container' ),
{
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
} );
mb_map.marker = new google.maps.Marker(
{
position: latLng,
title: 'Location',
map: mb_map.map,
draggable: true
} );
// Update current position info.
mb_map.geocodePosition( latLng );
} );
}
}
};
/**
* INIT on window load
*/
google.maps.event.addDomListener( window, 'load', mb_map.init );
</script>
Спасибо!
Редактировать: Согласнокомментарий, вот моя разметка:
<div id="map-container" style="min-width: 235px; height: 300px;">loading...</div>
<input type="submit" name="encode" id="encode" class="button-primary" value="Encode" onclick="mb_map.encodeAddress()">