谷歌地图鼠标悬停与标记和数据层行为

时间:2016-10-20 11:32:38

标签: javascript google-maps google-maps-api-3

在以下Google地图中,我在mouseovermouseout上有我的标记和数据层的事件监听器,它们会根据需要显示数据。

我遇到的问题是,当鼠标离开标记时,它不会显示数据层中的信息。我用一个标记和图层尝试了这个,行为按预期工作。我做错了什么?

我在marker图层上的每个map.data和事件侦听器上添加事件侦听器。

var map = null;
var markers = [];
var $info = $('#info');

var mapOptions = {
  center: null,
  zoom: 12,
  zoomControlOptions: {
    position: google.maps.ControlPosition.RIGHT_BOTTOM
  },
};

google.maps.event.addDomListener(
  window,
  'load',
  initialize
);

function initialize() {
  map = new google.maps.Map(
    document.getElementById('map-canvas'),
    mapOptions
  );

  addSchools();
  addWards();

  // Style wards
  map.data.setStyle(function(feature) {
    return {
      fillColor: 'green',
      fillOpacity: 0.2,
      strokeWeight: 1,
      strokeColor: 'grey'
    };
  });

  // Info on wards
  map.data.addListener('mouseover', function(event) {
    var title = event.feature.getProperty('title');
    $info.html(title).show();
  })

  map.data.addListener('mouseout', function(event) {
    $info.hide();
  })

};

function addWards() {
  var wards = JSON.parse(document.getElementById('wards').innerHTML);
  for (var i = 0; i < wards.length; i++) {
    var geoJsonLayer = wards[i];
    $.ajax({
      url: geoJsonLayer.Url,
      dataType: 'json',
      type: 'GET',
      title: geoJsonLayer["Ward Name"],
      success: function(data) {
        var layer = {
          "type": "FeatureCollection",
          "features": [
            { "type": "Feature",
             "geometry": data,
             "properties": {
               "title" : this.title
             }
            }
          ]
        }
        map.data.addGeoJson(layer);
      }
    })
  }
}

function addSchools() {
  var bounds = new google.maps.LatLngBounds();
  var schools = JSON.parse(document.getElementById('schools').innerHTML);
  for (var i = 0; i < schools.length; i++) {
    var latlng = new google.maps.LatLng(schools[i].Latitude, schools[i].Longitude);
    var marker = new google.maps.Marker({
      map: map,
      icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 6,
        fillColor: 'yellow',
        fillOpacity: 0.9,
        strokeWeight: 1,
        strokeColor: 'grey'
      },
      position: latlng,
      title: schools[i].School,
      zIndex: 999
    })

    google.maps.event.addListener(marker, 'mouseover', function() {
      $info.html(this.title).show();
    });

    google.maps.event.addListener(marker, 'mouseout', function() {
      $info.hide();
    });

    bounds.extend(latlng);
  }
  map.fitBounds(bounds);
};
html, body, #map-canvas {
  width: 100%;
  height: 100%;
  margin: 0;
}

#info {
  background: white;
  border: 1px solid gray;
  display: none;
  font-family: Roboto,Arial,sans-serif;
  overflow: hidden;
  padding: 5px;
  position: absolute;
  right: 10px;
  top: 10px;
  width: 400px;
}

#info h1 {
  border-bottom: 1px solid gray;
  font-size: 16px;
  margin: 0;
  padding-bottom: 4px;
  overflow: hidden;
  text-align: center;
  text-overflow: ellipsis;
  white-space: nowrap;
}

#info th {
  padding-right: 10px;
  text-align: left;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCQVBfiFu8nTpJHZ-O9TdoxCew4Fmf8ahU"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>	
<div id="map-canvas"></div>
<div id="info"></div>
<script type="application/json" id="schools">
[
  {
    "School": "University of Huddersfield",
    "Latitude": 53.643714,
    "Longitude": -1.777711
  },
  {
    "School": "Islamia Girls' High School",
    "Latitude": 53.644997,
    "Longitude": -1.787971
  },
  {
    "School": "Mount Pleasant Junior School",
    "Latitude": 53.635446,
    "Longitude": -1.793422
  },
  {
    "School": "Mount Pleasant Primary School",
    "Latitude": 53.635446,
    "Longitude": -1.793422
  },
  {
    "School": "Mount Pleasant Infant and Nursery School",
    "Latitude": 53.636496,
    "Longitude": -1.792781
  },
  {
    "School": "Thornton Lodge Nursery School",
    "Latitude": 53.636373,
    "Longitude": -1.799875
  },
  {
    "School": "Spring Grove Junior Infant and Nursery School",
    "Latitude": 53.643891,
    "Longitude": -1.791611
  },
  {
    "School": "Greenhead College",
    "Latitude": 53.647023,
    "Longitude": -1.793668
  },
  {
    "School": "Paddock Junior Infant and Nursery School",
    "Latitude": 53.644532,
    "Longitude": -1.809245
  },
  {
    "School": "Huddersfield Grammar School",
    "Latitude": 53.648293,
    "Longitude": -1.812012
  },
  {
    "School": "St David's School",
    "Latitude": 53.648293,
    "Longitude": -1.812012
  },
  {
    "School": "Birkby Infant and Nursery School",
    "Latitude": 53.656977,
    "Longitude": -1.791138
  },
  {
    "School": "Rathbone Choices",
    "Latitude": 53.649792,
    "Longitude": -1.788904
  },
  {
    "School": "Mountjoy House School",
    "Latitude": 53.651409,
    "Longitude": -1.793404
  },
  {
    "School": "Highfields School",
    "Latitude": 53.653566,
    "Longitude": -1.793379
  },
  {
    "School": "Edgerton College",
    "Latitude": 53.653885,
    "Longitude": -1.801109
  },
  {
    "School": "Birkby Junior School",
    "Latitude": 53.658602,
    "Longitude": -1.784578
  },
  {
    "School": "New Directions College",
    "Latitude": 53.647137,
    "Longitude": -1.772398
  }
]
</script>
<script type="application/json" id="wards">
	[
	  {
		"Ward Name":"Almondbury",
		"Url":"http://mapit.mysociety.org/area/135207.geojson"
	  },
	  {
		"Ward Name":"Ashbrow",
		"Url":"http://mapit.mysociety.org/area/8998.geojson"
	  },
	  {
		"Ward Name":"Crossland Moor and Netherton",
		"Url":"http://mapit.mysociety.org/area/135206.geojson"
	  },
	  {
		"Ward Name":"Dalton",
		"Url":"http://mapit.mysociety.org/area/9005.geojson"
	  },
	  {
		"Ward Name":"Greenhead",
		"Url":"http://mapit.mysociety.org/area/9003.geojson"
	  },
	  {
		"Ward Name":"Lindley",
		"Url":"http://mapit.mysociety.org/area/9002.geojson"
	  },
	  {
		"Ward Name":"Newsome",
		"Url":"http://mapit.mysociety.org/area/8996.geojson"
	  }
	]
</script>

1 个答案:

答案 0 :(得分:0)

如果标记位于多边形的顶部,则mouseover事件不会再次触发多边形。它仅在您第一次输入多边形时触发。

不确定是否是错误或预期的行为。解决此问题的一个选项是跟踪多边形的鼠标悬停状态,并在标记的mouseout事件上重新显示多边形信息。

// global variable
var state = {area: "", over: false};

// Info on wards
map.data.addListener('mouseover', function(event) {
  var title = event.feature.getProperty('title');
  $info.html(title).show();
  // save state
  state = {area: title, over: true};
})

map.data.addListener('mouseout', function(event) {
  $info.hide();
  // update state
  state.over = false;
})

// marker mouseout handler
google.maps.event.addListener(marker, 'mouseout', function() {
  $info.hide();
  console.log("mouseout:"+this.title);
  // if still over polygon, display info
  if (state.over) { $info.html(state.area).show() };
});

proof of concept fiddle

代码段

&#13;
&#13;
var map = null;
var markers = [];
var $info = $('#info');
var state = {
  area: "",
  over: false
};

var mapOptions = {
  center: null,
  zoom: 12,
  zoomControlOptions: {
    position: google.maps.ControlPosition.RIGHT_BOTTOM
  },
};

google.maps.event.addDomListener(
  window,
  'load',
  initialize
);

function initialize() {
  map = new google.maps.Map(
    document.getElementById('map-canvas'),
    mapOptions
  );

  addSchools();
  addWards();

  // Style wards
  map.data.setStyle(function(feature) {
    return {
      fillColor: 'green',
      fillOpacity: 0.2,
      strokeWeight: 1,
      strokeColor: 'grey'
    };
  });

  // Info on wards
  map.data.addListener('mouseover', function(event) {
    var title = event.feature.getProperty('title');
    $info.html(title).show();
    state = {
      area: title,
      over: true
    };
  })

  map.data.addListener('mouseout', function(event) {
    $info.hide();
    state.over = false;
  })

};

function addWards() {
  var wards = JSON.parse(document.getElementById('wards').innerHTML);
  for (var i = 0; i < wards.length; i++) {
    var geoJsonLayer = wards[i];
    $.ajax({
      url: geoJsonLayer.Url,
      dataType: 'json',
      type: 'GET',
      title: geoJsonLayer["Ward Name"],
      success: function(data) {
        var layer = {
          "type": "FeatureCollection",
          "features": [{
            "type": "Feature",
            "geometry": data,
            "properties": {
              "title": this.title
            }
          }]
        }
        map.data.addGeoJson(layer);
      }
    })
  }
}

function addSchools() {
  var bounds = new google.maps.LatLngBounds();
  var schools = JSON.parse(document.getElementById('schools').innerHTML);
  for (var i = 0; i < schools.length; i++) {
    var latlng = new google.maps.LatLng(schools[i].Latitude, schools[i].Longitude);
    var marker = new google.maps.Marker({
      map: map,
      icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 6,
        fillColor: 'yellow',
        fillOpacity: 0.9,
        strokeWeight: 1,
        strokeColor: 'grey'
      },
      position: latlng,
      title: schools[i].School,
      zIndex: 999
    })

    google.maps.event.addListener(marker, 'mouseover', function() {
      $info.html(this.title).show();
    });

    google.maps.event.addListener(marker, 'mouseout', function() {
      $info.hide();
      if (state.over) {
        $info.html(state.area).show()
      };
    });

    bounds.extend(latlng);
  }
  map.fitBounds(bounds);
};
&#13;
html,
body,
#map-canvas {
  width: 100%;
  height: 100%;
  margin: 0;
}
#info {
  background: white;
  border: 1px solid gray;
  display: none;
  font-family: Roboto, Arial, sans-serif;
  overflow: hidden;
  padding: 5px;
  position: absolute;
  right: 10px;
  top: 10px;
  width: 400px;
}
#info h1 {
  border-bottom: 1px solid gray;
  font-size: 16px;
  margin: 0;
  padding-bottom: 4px;
  overflow: hidden;
  text-align: center;
  text-overflow: ellipsis;
  white-space: nowrap;
}
#info th {
  padding-right: 10px;
  text-align: left;
}
&#13;
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCQVBfiFu8nTpJHZ-O9TdoxCew4Fmf8ahU"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<div id="map-canvas"></div>
<div id="info"></div>
<script type="application/json" id="schools">
  [ { "School": "University of Huddersfield", "Latitude": 53.643714, "Longitude": -1.777711 }, { "School": "Islamia Girls' High School", "Latitude": 53.644997, "Longitude": -1.787971 }, { "School": "Mount Pleasant Junior School", "Latitude": 53.635446,
  "Longitude": -1.793422 }, { "School": "Mount Pleasant Primary School", "Latitude": 53.635446, "Longitude": -1.793422 }, { "School": "Mount Pleasant Infant and Nursery School", "Latitude": 53.636496, "Longitude": -1.792781 }, { "School": "Thornton Lodge
  Nursery School", "Latitude": 53.636373, "Longitude": -1.799875 }, { "School": "Spring Grove Junior Infant and Nursery School", "Latitude": 53.643891, "Longitude": -1.791611 }, { "School": "Greenhead College", "Latitude": 53.647023, "Longitude": -1.793668
  }, { "School": "Paddock Junior Infant and Nursery School", "Latitude": 53.644532, "Longitude": -1.809245 }, { "School": "Huddersfield Grammar School", "Latitude": 53.648293, "Longitude": -1.812012 }, { "School": "St David's School", "Latitude": 53.648293,
  "Longitude": -1.812012 }, { "School": "Birkby Infant and Nursery School", "Latitude": 53.656977, "Longitude": -1.791138 }, { "School": "Rathbone Choices", "Latitude": 53.649792, "Longitude": -1.788904 }, { "School": "Mountjoy House School", "Latitude":
  53.651409, "Longitude": -1.793404 }, { "School": "Highfields School", "Latitude": 53.653566, "Longitude": -1.793379 }, { "School": "Edgerton College", "Latitude": 53.653885, "Longitude": -1.801109 }, { "School": "Birkby Junior School", "Latitude": 53.658602,
  "Longitude": -1.784578 }, { "School": "New Directions College", "Latitude": 53.647137, "Longitude": -1.772398 } ]
</script>
<script type="application/json" id="wards">
  [ { "Ward Name":"Almondbury", "Url":"http://mapit.mysociety.org/area/135207.geojson" }, { "Ward Name":"Ashbrow", "Url":"http://mapit.mysociety.org/area/8998.geojson" }, { "Ward Name":"Crossland Moor and Netherton", "Url":"http://mapit.mysociety.org/area/135206.geojson"
  }, { "Ward Name":"Dalton", "Url":"http://mapit.mysociety.org/area/9005.geojson" }, { "Ward Name":"Greenhead", "Url":"http://mapit.mysociety.org/area/9003.geojson" }, { "Ward Name":"Lindley", "Url":"http://mapit.mysociety.org/area/9002.geojson" }, {
  "Ward Name":"Newsome", "Url":"http://mapit.mysociety.org/area/8996.geojson" } ]
</script>
&#13;
&#13;
&#13;