注意:使用google地图api要想查看创建效果,必须使用代理服务器,中国大陆不能直接访问。
需求:本章博客将用最简单的方式介绍如何集成google地图,实现客户地理位置的展示。
思路:
1、在Account中自定义字段经纬度等;
2、编写Controller类来获取系统中所有客户的经纬度等数据;
3、编写VF,使用google map的api来展示地图控件,并将获取的客户地理信息解析出来填充到视图中;
4、以某种方式action来加载地图(这里将在tab中实现加载地图)。
相关代码:
1、LocationRemoter控制器
global with sharing class LocationRemoter {
@RemoteAction
global static List<Account> findAll() {
return [SELECT Id, Name, Location__Latitude__s, Location__Longitude__s
FROM Account];
}
}
2、编写AccountMap的visualforce
<apex:page sidebar="false" showheader="false" controller="LocationRemoter">
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
//加载google地图的js
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
//确定地图中心点,这里是中国的坐标
center: new google.maps.LatLng(29.56195, 106.551991),
zoom: 6
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
loadLocation();
}
function loadLocation() {
Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.LocationRemoter.findAll}',
function(result, event){
if (event.status) {
for (var i=0; i<result.length; i++) {
var id = result[i].Id;
var name = result[i].Name;
var lat = result[i].Location__Latitude__s;
var lng = result[i].Location__Longitude__s;
addMarker(id, name, lat, lng);
}
} else {
alert(event.message);
}
},
{escape: true}
);
}
function addMarker(id, name, lat, lng) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: name
});
//点击地图的marker,返回到对应客户的详细页面
google.maps.event.addListener(marker, 'click', function(event) {
window.top.location = '/' + id;
});
}
//为谷歌地图增加事件,当窗口加载时初始化地图,并将参数渲染到地图上
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</apex:page>
3、在Tab中new一个Visualforce Tabs,选择好自定义的visualforce page就OK了。
效果preview: