如何以自定义帖子类型显示Google地图

时间:2013-10-03 作者:Moaz Ateeq

我正在制作一个插件,其中使用了自定义类型的帖子,对于位置自定义类型,我如何显示任何位置的谷歌地图。输出将显示为enter image description here

1 个回复
最合适的回答,由SO网友:Prince Singh 整理而成

$prop_mapaddress 包含您的文本字段值:

<?php 
    if(isset($prop_mapaddress)) {
        global $post;
        global $wpdb;

        $fromat_address = trim($prop_mapaddress);
        $fromat_address = str_replace(" ","+",$fromat_address);
        $address_obj = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=".$fromat_address."&sensor=false");
        $address_obj =json_decode($address_obj);
        $latitude = $address_obj->results[0]->geometry->location->lat;
        $longitude = $address_obj->results[0]->geometry->location->lng;            
    ?>       
        <script>        
            var geocoder;       
            var map;      
            var lat = "<?php echo $latitude ?>";       
            var lng = "<?php echo $longitude;  ?>";

            function initialize() {       
                geocoder = new google.maps.Geocoder();       
                var latlng = new google.maps.LatLng(lat, lng);       
                var mapOptions = {        
                    zoom: 15,        
                    center: latlng,        
                    mapTypeId: google.maps.MapTypeId.ROADMAP       
                }        
                map = new google.maps.Map(document.getElementById(\'map-canvas\'), mapOptions);        
            } // map-convas would be id of div you want to show your map in  

            google.maps.event.addDomListener(window, \'load\', initialize);       
        </script>      
        <?php        
    }
?>
另外,在实际加载地图之前,不要忘记将Google API脚本排队:

wp_enqueue_script(\'google-map-api\',\'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false\'); 

结束