[英]Add marker to google map after map is initialised
我有一个使用Webbrowser控件来托管Google地图的ac#wpf项目。 请注意,这不是一个ASP项目。
如果在初始化例程期间添加标记,它们将起作用。 如果以后我使用InvokeScript从c#调用相同的例程,那么它将无法正常工作。
我希望有一个页面,我的C#代码可以通过调用各种JavaScript函数来根据需要添加/删除/更新标记。
我对javascript不太满意,我怀疑有一些我不理解的关键。
相关零件:
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=false&language="es""></script>
<script type="text/javascript">
var markersArray = [];
var gmap;
function initialize() {
var latlng = new google.maps.LatLng([GLAT], [GLONG]);
var myOptions = {
zoom: [ZOOM],
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
gmap = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
[MARKERLOCATIONS]
}
function AddMarker(Latitude, Longitude, Description) {
var latlng = new google.maps.LatLng(Latitude, Longitude);
var marker = new MarkerWithLabel({
position: latlng,
map: gmap,
title: Description,
labelContent: "1",
labelAnchor: new google.maps.Point(7, 30),
labelClass: "labels",
labelInBackground: false
});
</script>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</script>
我用实际的坐标和缩放替换了[GLAT],[GLONG]和[ZOOM]。 不久将在[LOCATIONS]中详细介绍。
MarkerWithLabel是Gary Little的代码http://code.google.com/p/google-maps-utility-library-v3/source/browse/tags/markerwithlabel/1.1.8/src/markerwithlabel.js
如果我将[MARKERLOCATIONS]替换为以下内容,则会在页面上获得所需的标记
AddMarker(51.47,0,"Greenwich")
用不同的坐标重复此语句可以为我提供尽可能多的标记。
如果我删除了[MARKERLOCATIONS],而在c#中执行了以下操作,则它不起作用(gmap是wpf Webbrowser):
gmap.LoadCompleted += new LoadCompletedEventHandler(gmap_LoadCompleted);
void gmap_LoadCompleted(object sender, NavigationEventArgs e)
{
// Add markers
foreach (Marker myM in ListMarker)
{
Object[] CallArgs = new Object[3];
CallArgs[0] = myM.Latitude.ToString();
CallArgs[1] = myM.Longitude.ToString();
CallArgs[2] = myM.ShortDescription;
object dummy = gmap.InvokeScript("AddMarker", CallArgs);
}
}
出于调试目的,我在AddMarker中放置了一个警报,然后依次传递了值; 我还创建了一个循环遍历markersArray内容的函数:
function ReportGPS() {
if (markersArray) {
for (var i = 0; i < markersArray.length; i++) {
//remove the marker from the map
alert(markersArray[i].toString());
}
}
}
public void Test()
{
object dummy = gmap.InvokeScript("ReportGPS");
}
如果我添加说5个标记,那么ReportGPS会给我5个警报。
因此,就像没有将它们添加到地图中一样。 同样,如果从初始化函数中调用AddMarker,它将起作用。
我想念什么?
我认为问题可能是您在执行initialize
函数之前调用了AddMarker
函数。 我有一些类似的代码,在调用AddMarker
函数之前,我使用C#调用了initialize
函数。
尝试从<body onload="initialize()">
删除initialze
调用,然后添加一个InvokeScript
函数调用以初始化地图。
void gmap_LoadCompleted(object sender, NavigationEventArgs e)
{
gmap.InvokeScript("initialize");
// Add markers
foreach (Marker myM in ListMarker)
{
Object[] CallArgs = new Object[3];
CallArgs[0] = myM.Latitude.ToString();
CallArgs[1] = myM.Longitude.ToString();
CallArgs[2] = myM.ShortDescription;
object dummy = gmap.InvokeScript("AddMarker", CallArgs);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.