Search code examples
blazor-server-sideblazorgooglemaps

How can I change MapOptions in the BlazorGoogleMaps Library at RunTime?


I am utilizing the BlazorGoogleMaps NuGet Package. You can see the source code at: GitHub

I would like to be able to change the MapType to Satellite and RoadMap during execution.

The following code has no impact.

_mapOptions.MapTypeId = MapTypeId.Satellite;
_map1.Options = _mapOptions;
//give the UI Access
await InvokeAsync(StateHasChanged);

I included this code in the MapRoutes.razor.cs => AddDirections() method.

Thank you

private async Task AddDirections()
{
    _durationTotalString = null;
    _distanceTotalString = null;
    if (await _dirRend.GetMap() is null)
    {
        await _dirRend.SetMap(_map1!.InteropObject);
    }

    _mapOptions.MapTypeId = MapTypeId.Satellite;
    _map1.Options = _mapOptions;
    //give the UI Access
    await InvokeAsync(StateHasChanged);

    //Adding a waypoint
    var waypoints = new List<DirectionsWaypoint>();
    waypoints.Add(new DirectionsWaypoint() { Location = "Bethlehem, PA", Stopover = true });

    //Direction Request
    var dr = new DirectionsRequest();
    dr.Origin = "Allentown, PA";
    dr.Destination = "Bronx, NY";
    dr.Waypoints = waypoints;
    dr.TravelMode = TravelMode.Driving;
    dr.DrivingOptions = new DrivingOptions()
    {
        DepartureTime = DateTime.Now.AddHours(1)
    };

    //Calculate Route
    _directionsResult = await _dirRend.Route(dr, new DirectionsRequestOptions
    {
        StripLegsStepsLatLngs = false,
        StripOverviewPath = false,
        StripOverviewPolyline = false,
        StripLegsStepsPath = false,
        StripLegsSteps = false
    });

    if (_directionsResult is null)
    {
        return;
    }
    var routes = _directionsResult.Routes.SelectMany(x => x.Legs).ToList();

    foreach (var route in routes)
    {
        _durationTotalString += route.DurationInTraffic?.Text;
        _distanceTotalString += route.Distance.Text;
    }
}

Solution

  • There is full server side demo page showing functionality. There are many more demo pages. https://github.com/rungwiroon/BlazorGoogleMaps/blob/master/ServerSideDemo/Pages/Maps.razor#L114

    
    private async Task ToggleMapType()
        {
            var mapTypeId = await _map1.GetMapTypeId();
    
            Console.WriteLine($"Map type is {mapTypeId}");
    
            if (mapTypeId != MapTypeId.Satellite)
            {
                await _map1.SetMapTypeId(MapTypeId.Satellite);
            }
            else
            {
                await _map1.SetMapTypeId(MapTypeId.Roadmap);
            }
        }