Reputation: 6370
I'm following this tuorial -https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
I've put in the code <?php echo the_field('post_code'); ?>
but I want to geocode it on load, not via an input and submit. How can I do that?
This is what I have:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.375599, -3.471680);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = '<?php echo the_field('post_code'); ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="float:left;height:250px; width:625px;margin-top:25px;"></div>
Upvotes: 0
Views: 110
Reputation: 7228
Call codeAddress()
in initialize()
passing address as parameter.
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.375599, -3.471680);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress(address);
}
Upvotes: 0
Reputation: 8401
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.375599, -3.471680);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress(); // This should do it. Assuming all the code is working.
}
Upvotes: 1