第一步:Familiarize yourself with Google Maps Embed API; 并注册API密钥:
与Javascript API不同,iframe嵌入选项没有使用限制,但没有那么多的选项/特性。确定所需的模式,并遵守所需的url格式和参数。
第二步:从用户处收集地址。为了便于讨论,我将展示一个示例,其中用户将地址添加到帖子的自定义元框字段中,并假设字段数据已validated/sanitized.
第三步:创建一个函数来构建iframe。下面是一个示例。。我相信这会更干净。示例函数可以使用包含地址字段的post的post$id调用,也可以从循环中调用,而不使用参数。
function build_map($id = NULL) {
/* Custom metabox field ids
/* Steet Address \'location_address\'
/* City \'location_city\'
/* State \'location_state\'
/* Postcode \'location_postcode\'
*/
if( empty($id) ){
$id = get_the_ID();
}
$address = array(
/*urlencode to replace spaces with +, etc.,. */
\'address\' => urlencode(get_post_meta($id, \'location_address\', TRUE)),
\'city\' => urlencode(get_post_meta($id, \'location_city\', TRUE)),
\'state\' => urlencode(get_post_meta($id, \'location_state\', TRUE)),
\'zip\' => urlencode(get_post_meta($id, \'location_postcode\', TRUE)),
);
/* Make sure we have each required field to build iframe*/
if( count( array_filter($address) ) < 4 ){
return;
}
/* contruct your output as you desire, this is my method: */
$op = \'<div class="google-map-embed">\';
$op .= \'<iframe width="{DESIRED WIDTH}" height="{DESIRED HEIGHT}" frameborder="0" style="border:0" \';
/* src attribute formatted for place mode: */
$op .= \'src="https://www.google.com/maps/embed/v1/place?q=\';
$op .= implode(\',\', $address);
$op .= \'&key={YOUR API KEY FROM STEP ONE GOES HERE}\';
/* configure optional zoom parameter: */
$op .= \'&zoom=11"></iframe></div>\';
print $op;
}