我有这个功能,我观察我的位置,同时我想显示从json数组传来的多个位置,但我需要观察它们不仅在地图上显示它们。到目前为止我得到了这个:
function initMap(userId,locations) {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay;
var icn="img/mechanic.png";
var meIcn="img/me.png";
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "red"
}
});
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: new google.maps.LatLng(53.529773,-113.509387), //ALBERTA
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var marker, i;
var infowindow = new google.maps.InfoWindow();
$.each(locations, function(index, element) {
watchMec = navigator.geolocation.watchPosition(function(position){
marker = new google.maps.Marker({
position: new google.maps.LatLng(
parseFloat(element.longitud), parseFloat(element.latitud)),
map: map,
icon: icn
});
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
// My position
watchId = navigator.geolocation.watchPosition(function(position){
lat = position.coords["latitude"];
lng = position.coords["longitude"];
markerMe = new google.maps.Marker({position: {lat: lat, lng: lng},
map:map, icon:meIcn});
});
return function() {
var distinationOrigin = new google.maps.LatLng(lat, lng); //My position
var destinationMarker = parseFloat(element.longitud) + ',' + '' +
parseFloat(element.latitud);
infowindow.setContent(element.datos);
infowindow.open(map, marker);
calculateAndDisplayRoute(directionsService, directionsDisplay,
distinationOrigin, destinationMarker, infowindow);
}
})(marker, i));
})
}
在萤火虫(mozilla)中我得到了一个typeError,但我不知道究竟在哪里。
在这种情况下如何使用watchposition?
提前致谢
答案 0 :(得分:0)
我解决了,问题是我将侦听器事件放在标记对象之外,因此标记变量未正确解析。解决方案是:
$.each(locations, function(index, element) {
watchMec = navigator.geolocation.watchPosition(function(position){
marker = new google.maps.Marker({
position: {lat:parseFloat(element.longitud), lng:parseFloat
(element.latitud)},
map: map,
icon:icn
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
// My position
watchId = navigator.geolocation.watchPosition(function(position){
lat = position.coords["latitude"];
lng = position.coords["longitude"];
markerMe = new google.maps.Marker({position: {lat: lat, lng: lng}, map: map, icon:meIcn});
});
return function() {
var distinationOrigin = new google.maps.LatLng(lat, lng); // MI POSICION
var destinationMarker = parseFloat(element.longitud) + ',' + '' + parseFloat(element.latitud);
infowindow.setContent(element.datos);
infowindow.open(map, marker);
calculateAndDisplayRoute(directionsService, directionsDisplay, distinationOrigin, destinationMarker, infowindow);
}
})(marker, i));
});
});