从数据库生成谷歌地图标记
本文关键字:地图 图标 谷歌 数据库 | 更新日期: 2023-09-27 18:07:10
你好,我正在尝试填充谷歌地图V3与多个标记从SQL Server数据库表
我将纬度经度保存在一个名为Location的列中,格式为38.425424,-5.477177
我的问题是标记没有出现在地图上
script type="text/javascript">
var markers = [
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
{
"title": '<%# Eval("Cust_Name") %>',
"Location": '<%# Eval("Location") %>',
"description": '<%# Eval("description") %>'
}
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
];
</script>
<script type="text/javascript">
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].Location),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.Location);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
<div class="panel-body" id="dvMap" style="height:280px;" >
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("select * from Customer");
rptMarkers.DataSource = dt;
rptMarkers.DataBind();
}
}
private DataTable GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
您将标记的纬度和经度呈现为单个字符串。google.maps.LatLng()构造函数接受两个参数,一个用于纬度,另一个用于经度。它看到你同时存储lat和long的单个字符串值,并抛出运行时错误,因为构造函数要求它们是两个单独的参数。
不要将lat和long作为一个字段存储在数据库中,而是将它们分成两个字段,然后在数组中将它们分成两个索引,然后将它们分别传递给google.maps.LatLng()构造函数的相应参数。
或者,如果不能更改数据库模式,则在将单个字符串传递给构造函数之前将其拆分为两个值。