Наведение курсора мыши на Google Maps с маркерами и поведением слоя данных

#javascript #google-maps #google-maps-api-3

#javascript #google-карты #google-maps-api-3

Вопрос:

На следующей карте Google у меня есть прослушиватели событий для mouseover и mouseout для моих маркеров и слоя данных, которые отображают данные соответствующим образом.

Проблема, с которой я сталкиваюсь, заключается в том, что когда мышь покидает маркер, она не отображает информацию со уровня данных. Я пробовал это с одним маркером и слоем, и поведение работает так, как ожидалось. Что я делаю не так?

Я добавляю прослушиватели событий на каждом 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. Я не вижу слои на карте… Я что-то упускаю?

2. Они должны отображаться в виде зеленых границ с желтыми маркерами, никаких проблем с запуском фрагмента кода здесь

Ответ №1:

mouseover Событие больше не запускается для полигонов, если маркер находится поверх полигона. Это срабатывает только при первом вводе полигона.

Не уверен, ошибка это или ожидаемое поведение. Одним из вариантов исправления этого было бы отслеживать состояние наведения курсора мыши на полигоны и повторно отображать информацию о полигоне в событии наведения курсора мыши на маркер.

 // 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() };
});
  

доказательство концепции скрипки

фрагмент кода:

 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);
};  
 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. Фрагмент не запускался, но доказательство концепции сделало свое дело