问题
I am loading a google map with GeoJSON, and after the map is loaded and the data layers are applied, I would like to trigger a click event at a specific point automatically for the user. Subsequently, they can click all over the map to interact with it.
So for the automatic load part, I tried something like this:
var x = new google.maps.LatLng(myLongitude, myLatitude);
google.maps.event.trigger(map.data, 'click', WHAT_GOES_HERE?);
but I can't figure out what goes in the last part of that function. The corresponding function for clicking is this:
map.data.addListener('click', function (event) {
...
code
...
}
The event fires, but event is null of course. I need (event) to be populated with a feature (that's what the type is expected to be) but I can't seem to figure out how to get the feature from a long/lat.
So I load my data layers, I have my long/lat, but I can't seem to retrieve a feature from the long/lat. Any suggestions on how to retrieve this?
回答1:
A (on)Click looks like this (let's say we put a marker there):
map.addListener('click', function (event) {
var position = {lat: event.latLng.lat(), lng: event.latLng.lng()}
//alert(JSON.stringify(position));
var marker = new google.maps.Marker({position: position, map: map});
});
So let's reverse this.
let's say you heve buttons that invoke a click on Brussels or Paris
<input type="button" value="click on Brussels" onclick="clickOnMap(50.85, 4.35)">
<input type="button" value="click on Paris" onclick="clickOnMap(48.84, 2.35)">
<script>
function clickOnMap(lat, lng) {
var event = {latLng: {}};
event.latLng.lat = function() { return lat };
event.latLng.lng = function() { return lng };
google.maps.event.trigger(map, 'click', event);
}
</script>
Clicking on the button will have the same effect as clicking on the map, on the same coordinates.
And of course you can call the function clickOnMap automatically.
Are you helped with this?
Edit: let's say you need more properties of event, like event.feature.getProperty("name");
Try adding something like this: I don't know what else is expected, but you can keep adding properties like this.
function clickOnMap(lat, lng, name) {
var event = {latLng: {}, feature: {}};
event.latLng.lat = function() { return lat };
event.latLng.lng = function() { return lng };
event.feature.getProperty = function(property) { return name; };
google.maps.event.trigger(map, 'click', event);
}
来源:https://stackoverflow.com/questions/45317081/google-maps-trigger-a-click-event-on-a-data-layer-at-a-specific-point-long-la