问题
Is there anyway i can put 2 hidden fields in a form and automatically put the Lat/Long into them from the user inputting a post code?
I don't really want to rely on the user dragging a marker on the Google map to plot the location.
Thanks in advance
Robbie
回答1:
To convert a UK postcode to a Latitude and Longitude, use Google's Geocoding API.
http://maps.googleapis.com/maps/api/geocode/json?address=POSTCODE&sensor=false
You will receive a JSON response which you can easily parse with JavaScript to populate your hidden fields.
回答2:
I would use JavaScript to control the form submission, and basically include two hidden fields within the form for lat/long. So, after user submits the address/zip code and etc basically use that information and query Google's Geocoding API and retrive the lat/long you are after. After the query, you can insert the queried Lat/Long into the hidden fields's values and then submit using JavaScript.
hidden field in the form and the attach function to the onclick on the submit button of the form:
<input type='hidden' name='lat' id='lat' value='' />
<input type='hidden' name='lng' id='lng' value='' />
<input type="button" value="Send" onClick="javascript:querieBeforeSubmit();">
This is the JavaScript that queries geoapi and insert value into hidden field
<script type='text/javascript'>
function querieBeforeSubmit(){
//queries Google Geoapi w/ address etc
var lat = //retrived lat
var lng = //retrived lng
document.getElementById('lat').value = lat;
document.getElementById('lng').value = lng;
form.submit();
}
</script>
回答3:
Got it sorted by mashing this page - http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/getlatlng.html
Works really well.
来源:https://stackoverflow.com/questions/4923124/google-maps-google-local-search-generate-lat-long-from-uk-postcode