0

I have a wordpress site with a large number of pages, each page represent a physical location. Now for each page I would like to display a google map based on the address. I know I can do this by installing a google map plugin, but that requires that I manually, for every post, create a location based on the address and add a shortcode to the post/page that results in a google map. This is a LOT of work for this site with hundreds of locations.

I would like to be able to create an "address-custom-field" for each post programmatically.

This is where I am now:

<div id="map_canvas" style="width: 190px; height: 130px; margin-top: 5px;"></div> 
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=mykey&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var myOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
</script>

How do i change center: new google.maps.LatLng(-34.397, 150.644), into an adress?

4

2 回答 2

0

You can edit the template file for these pages and embed a google map similarly to this example: https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

Note that it'll be better to perform geo coding of all addresses once, and save the coordinates in different custom field for each page -- that way you won't need to create geocoding request on each page load.

Here is untested code that should be close to what you need:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

<!-- in the body --> 

<div id="map-canvas"></div>

<script>
    (function () {
        var map = new google.maps.Map(document.getElementById('map-canvas'), {
            zoom: 8,
            center: new google.maps.LatLng(-34.397, 150.644),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var address = <?php echo json_encode(get_post_meta(get_the_id(), 'address-custom-field', true)) ?>" ;

        (new google.maps.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);
            }
        });
    })()
</script>
于 2013-08-15T11:34:17.150 回答
0

I'm in the middle of this myself... Its no easy feat that's for sure. It involves AJAX (WordPress version) Geo-Data-Store plugin to geocode your posts and pages and custom loops.

Either way you have to add location data to each post.

于 2013-08-15T13:02:08.293 回答