5 Minute Snack: TMSWebGMaps: How to zoom in on all markers — reliably
I already posted about how easy it is to add markers to a map using TMSWebGMaps in a VCL Forms Application. However, the documentation is rather slim on how to focus the map on all the markers added. You might find the method MapZoomTo sooner or later. This method expects the bounds to be specified and for that you may use Map.Markers.Bounds which will yield the bounds encompassing all the markers that have been added to the map.
The approach is very logical and — as always — if you know which method and propery to use it makes very much sense and it is easy to remember. Just finding it for the first time is always a challenge.
Looking at the following code snippet that iterates over a data set and adds exactly one marker for every record, we can also see the call to MapZoomTo at the end. Accoding to the documentation and also to what I just wrote, this should work:
// clear map markers Map.Markers.Clear; while Data_exists do begin // get LState instance with details // on US State, esp. latitude and longitude // ... // ... LMarker := Map.Markers.Add( LState.Latitude, LState.Longitude ); LMarker.Text := LState.ShortName; LMarker.Clickable := True; LMarker.Data := 'some essential data'; // next record... // ... end; // zoom and move map so all markers // are visible... Map.MapZoomTo(Map.Markers.Bounds);
To be blunt: Depending on the internet connection available it won’t work. Especially if you make the call to MapZoomTo right after the start of the application, the call will lead to nothing. It will simply be ignored by the Google API. You always have to remember that any call to the WebGMaps framework will lead to some sort of interaction with the Google API sooner or later. If that API is not able to receive the call or has not processed all the previous calls, the call will be ignored and not queued.
The solution is again rather simple, but you need to know the fact that the map control has to be ready to be zoomed or panned. It is ready right after the download has completed. Thus, we can use the event called MapDownloadFinish (granted, OnMapDownloadDidFinish would have been a much better name) of the map control:
procedure TFrmMain.MapDownloadFinish(Sender: TObject); begin Map.MapZoomTo(Map.Markers.Bounds); end;
The instance to Map and also Map.Markers.Bounds can be called at any time after the markers have been added. As the map is owned by the form, this requires no additional variables etc. Putting the call to zoom into the event makes certain that the control is ready.
In order to not miss these things, TMS offers a FAQ for all their components. You can find the FAQ for the VCL mapping component here. Furthermore, you also find a solution how to zoom in on all the markers.
Finally, be sure to subscribe to their newsletter. It contains valuable technical information for all products and is released frequently.