Determine when drawing of Geojson is complete in Google Maps API - google-maps

Is there an event that gets fired when drawing of all features have completed when using the loadGeoJson() method in Google Maps API?
I read that you can listen for "idle" state of the map, but it seems like the map is considered idle when the load is complete, but before features are drawn.
see fiddle below:
https://jsfiddle.net/z3tu0epb/
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(40.755690, -73.975938)
});
// Load GeoJSON.
map.data.loadGeoJson(
'https://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nybb/FeatureServer/0/query?where=1=1&outFields=*&geometryPrecision=8&outSR=4326&f=geojson');
google.maps.event.addListenerOnce(map, 'idle', function() {
alert("map is idle");
});
}
I also know about the addFeature() listener which gets fired when any feature is added to the map, but I need the alert() to run after all the features are added to the map.
Thanks,

I'm afraid there is no feasible way to capture "after drawing all features" event for Data layer. It could be possible if the Data layer had exposed the instance of Drawing manager that is used internally. In this case you could listen to the overlaycomplete event
https://developers.google.com/maps/documentation/javascript/reference#OverlayCompleteEvent
But the Data layer doesn't expose its Drawing manager instance publicly, so you cannot add a listener.
https://developers.google.com/maps/documentation/javascript/reference#Data
The unique thing that you can do is to figure out when all features were loaded (added to collection). In this case you can use a callback function of loadGeoJson(url:string, options?:Data.GeoJsonOptions, callback?:function(Array<Data.Feature>))
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(40.755690, -73.975938)
});
// Load GeoJSON.
map.data.loadGeoJson(
'https://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nybb/FeatureServer/0/query?where=1=1&outFields=*&geometryPrecision=8&outSR=4326&f=geojson',
{},
function(features) {
alert("Loaded " + features.length + " features");
});
google.maps.event.addListenerOnce(map, 'idle', function() {
alert("map is idle");
});
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap">
</script>
Also, feel free to file a feature request for such event in the Google issue tracker

Related

How to detect enter and exit streetView in Google Maps API v3

Is there a way to detect when a user enters and exits StreetView in Google Maps under API v3?
I want to trigger an existing 'Hide Menu' function when the user enters StreetView (as the menu isn't relevant) and then re-show the menu when they exit.
Observe the visible_changed-event of the streetView, the visible-property will be true or false (open or closed)
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.5498783, 13.425209),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
google.maps.event.addListener(map.getStreetView(),'visible_changed',function(){
alert('streetview is ' +(this.getVisible()?'open':'closed'));
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,body,#map-canvas { height: 100%; margin: 0; padding: 0; }
<script src="https://maps.googleapis.com/maps/api/js?v=3&.js"></script>
<div id="map-canvas"></div>
You have to use the visible_changed event listener and also add a doAlert() function. This would enable the street view to make an alert on entry for the street view and also while exitting the street view.

Using Jquery Mobile v1.4.2 with Google Maps v3

I am attempting to write some code to display google maps in satellite view inside of JQuery Mobile/HTML. So far to no success, seems all the example code is out of date or not functioning. What i'm looking for is displaying a google map satellite image, getting two X/Y coordinates from code (these will actually be coming from a MySQL database query), and placing a marker on the map at that location. The code I have is below. When I run the full website code I can navigate to the maps page and see the header and back button but the map is not displaying.
Note this is called when a button is pressed on the main page.
HTML:
<div data-role="page" id="map-page" data-url="map-page" data-add-back-btn="true">
<div data-role="header" data-theme="a">
<h1>Maps</h1>
</div>
<div role="main" class="ui-content" id="map-canvas">
<!-- map loads here... -->
</div>
</div>
JavaScript:
$( document ).on( "pageinit", "#map-page", function() {
var defaultLatLng = new google.maps.LatLng(33.061414, -83.226385); // Default to Lockerly Arb when no geolocation support
if ( navigator.geolocation )
{
function success(pos)
{
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error)
{
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
}
else
{
drawMap(defaultLatLng); //No geolocation support, show default map
}
function drawMap(latlng)
{
var myOptions =
{
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title: "Lockerly Arboretum!"
});
}
});
CSS:
`//Google Maps CSS
#map-page, #map-canvas
{
width: 100%; height: 100%; padding: 0;
}`

Google Map layer refresh with Geojson

I am able to plot data onto google maps using geojson. I now want to refresh the markers every 10 seconds. How can I do this? In my example below the json file would refresh on my local server. How can I change the properties/ position of the same marker?
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var layer1;
var layer2;
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
layer1 = map.data.loadGeoJson('http://localhost/envitia.its.webclient/myjson.json');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map">
</div>
</body>
</html>
Can you just use the setInterval() function in javascript? In you initialize() function, just wrap the layer1 command in a setInterval() with a time of 10 seconds.
I had a similar question and the comment from Todd is correct. Per the Google Maps API, the GeoJSON functions just load a bunch of features in into the map. To remove them, you can either
Remove every feature and start over
Implement some logic to remove only the features that need to be removed and selectively add ones not already on the map
It varies slightly if you use the .addGeoJson() function vs .loadGeoJson(). If you use the first one, you can do something like
if (mapFeatures != null) {
for (var i = 0; i < mapFeatures.length; i++) {
map.data.remove(mapFeatures[i]);
}
}
geoJSON = jQuery.parseJSON(json.data);
mapFeatures=map.data.addGeoJson(geoJSON);
mapFeatures is an array of Data.Feature objects which are just iterated and removed. If you use the .loadGeoJson() method instead, then you can use the forEach() method to iterate though the collection in the map object.
Have a look at the API reference. There is also a contains() method if you want to implement selective feature removal
https://developers.google.com/maps/documentation/javascript/reference#Data

How to remove all events from a KML layer in Google Maps API V3

I'm making a web application that uses google maps to help with solar deployment. In essence, I'm loading a google map in full screen and overlaying KML layers using this code:
window.solarLayer = new google.maps.KmlLayer({
url: 'somelink'
});
window.solarLayer.setMap(window.map);
Another feature of this application is that a user is able to click anywhere in the map, and using the latitude and logitude at the click point, it would return solar data to the user.
This all works fine by using a click event handler as such:
google.maps.event.addListener(map, 'click', function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
});
However, the portion of the map that has the KML layer only registers clicks for the layer and does not access the click event I created...
Does anyone know how to disable click events for KML layers? or how to make my event listener supersede that of the KML layer?
I have tried getting the lat and long by using a click event on the KML layer as well as the map but that only yields a static lat long of where that layer is positioned, not where the user actually clicks.
Thanks for any help in advance!
Set the clickable option of the KmlLayer to false.
from the KmlLayerOptions documentation:
clickable| Type: boolean
If true, the layer receives mouse events. Default value is true.
code snippet:
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
window.solarLayer = new google.maps.KmlLayer({
url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
clickable: false
});
window.solarLayer.setMap(window.map);
google.maps.event.addListener(map, 'click', function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
document.getElementById('coords').innerHTML = event.latLng.toUrlValue(6);
console.log(latitude + ', ' + longitude);
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="coords"></div>
<div id="map_canvas"></div>

How to get cordinates by clicking on a google map

I'm new to google maps and want to use google map javascript API to display houses as markers. I want a person to be able to click on the map to place a marker, which can be clicked again to be removed or dragged to another location on the map. Then, I want the script to get the cordinates(lat and long) so that I can ad it to a database table. Any idea how I should do this? I'm using PHP in codeIgniter.
A good place to start would be to check out the reference manual: http://code.google.com/apis/maps/documentation/javascript/reference.html
If you look at map there you can see that it has an event called "click". What you do is after your map has been initialized you make an eventlistener, that listens to the click event. When that occurs you then place a marker on that location, and add an eventlistener on that marker for the click event if you want to remove it, or make it draggable if you want to drag it.
Remember to store your markers in an array if you ever want to use the information they are holding again.
I hope this helped.
I am late to the party. Please find below code snipet.
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var marker;
map.addListener('click', function(e) {
if(marker){
var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
marker.setPosition(latlng);
}else{
marker = new google.maps.Marker({
position: {lat : e.latLng.lat(), lng : e.latLng.lng()},
map: map
})
}
alert("lat : "+e.latLng.lat()+ "; lng : "+e.latLng.lng())
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPpCPQOwkMotaDj0IgHQ7HDAE8cz6-4U&callback=initMap"
async defer></script>