makeicon | Generates mobile app icons in all resolutions for both iOS | Mobile Application library
kandi X-RAY | makeicon Summary
Support
Quality
Security
License
Reuse
- save image
- getImageBase64 returns base64 encoded image base64
- getImageFromBase64 gets an image from base64 string
- main is the main entry point
- save image to given directory
- NewMyImageFromBase64 returns a new Image struct
makeicon Key Features
makeicon Examples and Code Snippets
Trending Discussions on makeicon
Trending Discussions on makeicon
QUESTION
I am constructing a shiny app. The app displays a few GPS points on a map. Each point has a type
and each type
displays a different icon (or image).
I want to display a legend (a reactive legend) that appears only if the user selects something from the menu input_gr_letter
with the relevant icon (or image) and label for that selection.
Problem: I am neither able to make the legend appear only is a use selects something from input_gr_letter
nor am I able to show only in the legend what has been selected in input_gr_letter
.
Below is a reproductible example & images describing the current/expected behavior:
library(shiny)
library(shinyWidgets)
library(leaflet)
library(leaflegend)
library(dplyr)
library(sp)
library(raster)
library(rgdal)
library(rgeos)
points <- c("A", "A", "B", "B")
lat <- c(9,10,11,10)
lon <- c(11,10,2,12)
type <- c("alpha","beta","theta","gamma")
df <- data.frame(points,lat,lon,type)
coordinates(df)<-~lat+lon
proj4string(df) <- CRS("+proj=longlat +datum=WGS84 +no_defs")
library(leaflegend)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map1", width = "100%", height = "100%"),
absolutePanel(left = 10, bottom = 10, draggable = TRUE,
selectInput(inputId = "input_letter", label = "Select Letter",
choices = c("A","B")),
selectInput(inputId = "input_gr_letter", label = "Select Gr Letter",
choices = c("alpha","beta","theta","gamma"),
multiple = TRUE)
))
# List of Icons
listofIcons <- iconList(
alpha = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/yellow-circle-emoji.png", iconWidth = 10, iconHeight = 10),
beta = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/orange-circle-emoji.png", iconWidth = 10, iconHeight = 10),
theta = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/purple-circle-emoji.png", iconWidth = 10, iconHeight = 10),
gamma = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/red-circle-emoji.png", iconWidth = 10, iconHeight = 10)
)
server <- function(input, output, session) {
# Create the map
output$map1 <- renderLeaflet({
leaflet(
option = leafletOptions(attributionControl=FALSE)) %>%
addTiles()
})
data_point <- reactive({
df[df@data$points == input$input_letter & df@data$type == input$input_gr_letter,]
})
# Reactive Map ---------------------------------
observeEvent(list(input$input_letter, input$input_gr_letter), {
leafletProxy("map1") %>%
addMarkers(data = data_point(),
icon = ~listofIcons[type]) %>%
addLegendImage(images = c("https://img.icons8.com/emoji/48/000000/yellow-circle-emoji.png",
"https://img.icons8.com/emoji/48/000000/orange-circle-emoji.png",
"https://img.icons8.com/emoji/48/000000/purple-circle-emoji.png",
"https://img.icons8.com/emoji/48/000000/red-circle-emoji.png"),
labels = unique(df$type))
})
}
shinyApp(ui, server)
ANSWER
Answered 2021-Dec-08 at 19:00library(shiny)
library(shinyWidgets)
library(leaflet)
library(leaflegend)
library(dplyr)
library(sp)
library(raster)
library(rgdal)
library(rgeos)
points <- c("A", "A", "B", "B")
lat <- c(9,10,11,10)
lon <- c(11,10,2,12)
type <- c(alpha= "alpha",beta = "beta",theta = "theta",gamma = "gamma")
df <- data.frame(points,lat,lon,type)
coordinates(df)<-~lat+lon
proj4string(df) <- CRS("+proj=longlat +datum=WGS84 +no_defs")
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map1", width = "100%", height = "100%"),
absolutePanel(left = 10, bottom = 10, draggable = TRUE,
selectInput(inputId = "input_letter", label = "Select Letter",
choices = c("A","B")),
selectInput(inputId = "input_gr_letter", label = "Select Gr Letter",
choices = c("alpha","beta","theta","gamma"),
multiple = TRUE)
))
# List of Icons
listofIcons <- iconList(
alpha = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/yellow-circle-emoji.png", iconWidth = 10, iconHeight = 10),
beta = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/orange-circle-emoji.png", iconWidth = 10, iconHeight = 10),
theta = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/purple-circle-emoji.png", iconWidth = 10, iconHeight = 10),
gamma = makeIcon(iconUrl = "https://img.icons8.com/emoji/48/000000/red-circle-emoji.png", iconWidth = 10, iconHeight = 10)
)
server <- function(input, output, session) {
# Create the map
output$map1 <- renderLeaflet({
leaflet(
option = leafletOptions(attributionControl=FALSE)) %>%
addTiles()
})
data_point <- reactive({
df[df@data$points == input$input_letter & df@data$type %in% input$input_gr_letter,]
})
# Reactive Map ---------------------------------
imgs <- c(alpha = "https://img.icons8.com/emoji/48/000000/yellow-circle-emoji.png",
beta = "https://img.icons8.com/emoji/48/000000/orange-circle-emoji.png",
theta = "https://img.icons8.com/emoji/48/000000/purple-circle-emoji.png",
gamma = "https://img.icons8.com/emoji/48/000000/red-circle-emoji.png")
observeEvent(list(input$input_letter, input$input_gr_letter), {
if(is.null(input$input_gr_letter)) return(leafletProxy("map1") %>% removeControl("legend"))
leafletProxy("map1") %>%
addMarkers(data = data_point(),
icon = ~listofIcons[type]) %>%
removeControl("legend") %>%
addLegendImage(images = imgs[input$input_gr_letter],
labels = type[input$input_gr_letter], layerId = "legend")
}, ignoreInit = T)
}
shinyApp(ui, server)
QUESTION
I'm using the Google maps utility library to generate an icon for my markers, and the setColor is not working, every color I set, is a different shade of blue, it's not my color, and it's also got a black stroke around, which I don't want.
this is the code:
for (place in location.locations) {
val locationPoz = LatLng(place.lat, place.long)
boundsBuilder.include(locationPoz)
//Here is the icon part
val icon = IconGenerator(requireContext())
icon.setColor(R.color.red)
val fIcon = icon.makeIcon("${place.price}€")
val marker = MarkerOptions()
.position(locationPoz)
.title(place.name)
.icon(BitmapDescriptorFactory.fromBitmap(fIcon))
.alpha(5f)
googleMap.addMarker(marker)
}
ANSWER
Answered 2021-Dec-03 at 15:52I think you can only use one of the provided values in https://googlemaps.github.io/android-maps-utils/javadoc/com/google/maps/android/ui/IconGenerator.html
Try
~icon.setColor(IconGenerator.STYLE_RED)
~
EDIT: I misread, I think. The STYLE_* values would have to be used like icon.setStyle(IconGenerator.STYLE_RED)
That doesn't yet solve your problem of the border you don't want, so instead, you would need to provide your own background drawable with setBackground
QUESTION
I'm starting a Shiny app with a leaflet map in it.
I need the user to be able to place two separate markers (origin & destination) on the map, and potentially replace them later on.
So what I did is create an origin button and a destination button, so that when the user clicks one of them, they'll place or update the corresponding marker with their next click on the map.
library(shiny)
library(shinyWidgets)
library(leaflet)
library(RColorBrewer)
library(osrm)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(top = 10, right = 10,
actionButton("change_orig", "Origine"),
actionButton("change_dest", "Destination"),
)
)
server <- function(input, output, session) {
origin_icon = makeIcon("https://static.thenounproject.com/png/1477944-200.png",
iconWidth=24, iconHeight=30)
destination_icon = makeIcon("https://static.thenounproject.com/png/924206-200.png",
iconWidth=24, iconHeight=30)
output$map <- renderLeaflet({
leaflet() %>% addTiles(providers$OpenStreetMap) %>%
addProviderTiles(providers$OpenStreetMap, group="Open Street Map") %>%
addProviderTiles(providers$OpenTopoMap, group="Open Topo Map") %>%
fitBounds(2.907730, 45.856550, 3.310954, 45.714034) %>%
addLayersControl(
baseGroups = c("Open Street Map", "Open Topo Map")
)
})
# When "Origin" is selected,
# a click on the map will (re)place the origin marker.
observeEvent(input$change_orig, {
observeEvent(input$map_click, {
click = input$map_click
leafletProxy('map')%>%
clearGroup("origin") %>%
addMarkers(lng=click$lng, lat=click$lat, icon=origin_icon,
group="origin")
})
})
# When "Destination" is selected,
# a click on the map will (re)place the destination marker.
observeEvent(input$change_dest, {
observeEvent(input$map_click, {
click = input$map_click
leafletProxy('map') %>%
clearGroup("destination") %>%
addMarkers(lng=click$lng, lat=click$lat, icon=destination_icon,
group="destination")
})
})
}
shinyApp(ui, server)
And I'm facing a couple problems here.
- If I have already clicked on the map before clicking on one of the buttons, the app will consider the previous click and add a marker there.
- Most importantly: even though I create origin marker and destination markers in separate groups,
clearGroup
deletes both destination and origin markers and recreates both at the same location.
How could I make sure to only create or replace one marker without affecting the other?
And how could I only listen to the click event after button's been selected?
ANSWER
Answered 2021-Sep-17 at 14:47So I ended up going for a radioButtons
instead of two actionButton
s.
Then in the observeEvent
for map_click
, I used a simple if
to check which of the radio buttons was selected:
library(shiny)
library(shinyWidgets)
library(leaflet)
library(RColorBrewer)
library(osrm)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(top = 10, right = 10,
radioButtons(
'orig_dest_switch',
"Changer l'origine ou la destination",
choices = c("Origine", "Destination"),
choiceValues = c("orig", "dest"),
inline = TRUE),
)
)
server <- function(input, output, session) {
origin_icon = makeIcon("https://static.thenounproject.com/png/1477944-200.png",
iconWidth=24, iconHeight=30)
destination_icon = makeIcon("https://static.thenounproject.com/png/924206-200.png",
iconWidth=24, iconHeight=30)
output$map <- renderLeaflet({
leaflet() %>% addTiles(providers$OpenStreetMap) %>%
addProviderTiles(providers$OpenStreetMap, group="Open Street Map") %>%
addProviderTiles(providers$OpenTopoMap, group="Open Topo Map") %>%
fitBounds(2.907730, 45.856550, 3.310954, 45.714034) %>%
addLayersControl(
baseGroups = c("Open Street Map", "Open Topo Map")
)
})
observeEvent(input$map_click, {
click = input$map_click
# Vérifier si l'on update le marker d'origine ou de destination
if(input$orig_dest_switch=="Origine"){
origin = list(lng=click$lng, lat=click$lat)
leafletProxy('map')%>%
clearGroup("origin") %>%
addMarkers(lng=click$lng, lat=click$lat, icon=origin_icon,
group="origin")
} else {
destination = list(lng=click$lng, lat=click$lat)
leafletProxy('map')%>%
clearGroup("destination") %>%
addMarkers(lng=click$lng, lat=click$lat, icon=destination_icon,
group="destination")
}
})
}
shinyApp(ui, server)
QUESTION
Android Google Map Cluster icon ignores custom icon on zoom out. Any suggestion how to fix it?
override fun onBeforeClusterRendered(cluster: Cluster, markerOptions: MarkerOptions) {
mClusterIconGenerator.setBackground(context?.let { ContextCompat.getDrawable(it, R.drawable.map_cluster_item) })
mClusterIconGenerator.setTextAppearance(R.style.WhiteTextAppearance)
val icon = mClusterIconGenerator.makeIcon(cluster.size.toString())
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
ANSWER
Answered 2020-Jul-14 at 09:22Fixed with override of getDescriptorForCluster
private val mClusterIconGenerator = IconGenerator(context).apply {
setBackground(context?.let { ContextCompat.getDrawable(it, R.drawable.map_cluster_item) })
setTextAppearance(R.style.WhiteTextAppearance)
}
override fun onBeforeClusterRendered(cluster: Cluster, markerOptions: MarkerOptions) {
val icon = mClusterIconGenerator.makeIcon(cluster.size.toString())
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
override fun getDescriptorForCluster(cluster: Cluster): BitmapDescriptor {
val icon = mClusterIconGenerator.makeIcon(cluster.size.toString())
return BitmapDescriptorFactory.fromBitmap(icon)
}
QUESTION
I am attaching a tag to a Marker when I add it to GoogleMap like this:
val icon = IconGenerator(context).makeIcon("${listing.cost}$")
map.addMarker(
MarkerOptions().position(LatLng(address.latitude, address.longitude))
.icon(BitmapDescriptorFactory.fromBitmap(icon!!))
).tag = listing
Is it possible to remove the marker later if it matches the tag I assigned it to?
Listing is an object on the Database that I am adding to GoogleMap, and I want to remove the listing Marker when it is removed from the Database. Thanks.
ANSWER
Answered 2020-Jul-01 at 18:49I believe the answer is No. I ended up saving the Marker in a ViewModel hashMap variable that has Marker id as key, and actual Marker Object as Value.
I stored the Marker's id on a database then I get the actual Marker from the hashMap using the id as key, then remove it.
QUESTION
In my app having cluster on map, Top/Main cluster marker show total marker count, click on that show all sub cluster item marker.
In Cluster item(Sub cluster marker) show round background with different colour and in between that show image from the URL ( get from the web service response), cluster item show image properly but my issue is that after refreshing last response image URL overwrite with all marker image, means all cluster item show same image instead of different one.
Please any one can help to this overwrite issue. my code is following.
private class RenderClusterInfoWindow extends DefaultClusterRenderer {
private final IconGenerator mClusterIconGenerator = new IconGenerator(getActivity());
private final IconGenerator iconGenerator = new IconGenerator(getActivity());
ImageView imageView;
int markerWidth;
int markerHeight;
private DisplayImageOptions options;
RenderClusterInfoWindow(Activity context, GoogleMap map, ClusterManager clusterManager) {
super(context, map, clusterManager);
// Main inflate view it show number data available inside cluster
View multiProfile = getLayoutInflater().inflate(R.layout.inflate_cluster, null);
mClusterIconGenerator.setContentView(multiProfile);
markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
// inflator its show image from the response url. (cluster item)
View clusterITEM = getLayoutInflater().inflate(R.layout.inflate_cluster_item, null);
iconGenerator.setContentView(clusterITEM);
imageView = clusterITEM.findViewById(R.id.imageClusterPIN);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(markerWidth, markerHeight);
layoutParams.gravity = Gravity.CENTER;
imageView.setLayoutParams(layoutParams);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.mipmap.image_icn)
.showImageOnFail(R.mipmap.image_icn)
.cacheInMemory(false)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
@Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (googleMap.getCameraPosition().zoom > 19.0) {
setClusterSize = 2;
} else {
setClusterSize = 4;
}
}
});
}
if (setClusterSize == 2) {
return cluster.getSize() > cluster.getSize();
} else {
return cluster.getSize() > setClusterSize;
}
}
@Override
protected void onClusterRendered(Cluster cluster, Marker marker) {
super.onClusterRendered(cluster, marker);
}
@Override
protected void onBeforeClusterItemRendered(ModelClusterBikeList item, MarkerOptions markerOptions) {
iconGenerator.setBackground(
ContextCompat.getDrawable(getActivity(), R.drawable.round_asset));
ImageLoader.getInstance().displayImage(item.getAssets_img_url(), imageView, options);
// Issue is here , overwrite image url here with all marker./cluster item.
Bitmap icon = iconGenerator.makeIcon(item.getAssets_img_url());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
markerOptions.title(item.getId());
markerOptions.draggable(true);
super.onBeforeClusterItemRendered(item, markerOptions);
}
@Override
protected void onBeforeClusterRendered(Cluster cluster, MarkerOptions markerOptions) {
mClusterIconGenerator.setBackground(null);
Bitmap icon = mClusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
@Override
protected void onClusterItemRendered(ModelClusterBikeList clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
}
}
I also try with putting all code of "onBeforeClusterItemRendered" into onClusterItemRendered but getting same result, same overwrite last url with all cluter item.
ANSWER
Answered 2020-May-15 at 13:52Hello @Topsy change code as per folloding it will work for you.
First replace onBeforeClusterItemRendered method with following code.
@Override
protected void onBeforeClusterItemRendered(ModelClusterBikeList item, MarkerOptions
markerOptions) {
icon = iconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).
title(item.getAssets_img_url());
markerOptions.title(item.getId());
markerOptions.draggable(true);
super.onBeforeClusterItemRendered(item, markerOptions);
}
and then replace onClusterItemRendered method with following code.
@Override
protected void onClusterItemRendered(ModelClusterBikeList clusterItem, Marker
marker) {
if (getActivity() != null) {
Glide.with(getActivity())
.asBitmap()
.load(clusterItem.getAssets_img_url())
.error(R.drawable.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(new CustomTarget() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable
Transition transition) {
try {
if (googleMap != null) {
iconGenerator.setBackground(
ContextCompat.getDrawable(getActivity(),
R.drawable.round_asset));
imageView.setImageBitmap(resource);
imageView.buildDrawingCache();
Bitmap icon = iconGenerator.makeIcon();
if (icon != null) {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(icon));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
}
QUESTION
I have a data frame that contains a list of all sports venues in my state.
Here is a list of the column names in my data frame (pretty self explanatory):
[1] "City" "latitude" "longitude" "Rank" "Population" "County"
[7] "Desc"
I have created all icons below:
library(leaflet)
NHL <- makeIcon(
iconUrl = "https://www-league.nhlstatic.com/images/logos/league-dark/133-flat.svg",
iconWidth = 31*215/230,
iconHeight = 31,
iconAnchorY = 16,
iconAnchorX = 31*215/230/2)
MLB <- makeIcon(
iconUrl = "https://www.mlbstatic.com/team-logos/league-on-dark/1.svg",
iconWidth = 31*215/230,
iconHeight = 31,
iconAnchorY = 16,
iconAnchorX = 31*215/230/2)
MLS <-makeIcon(
iconUrl = "https://league-mp7static.mlsdigital.net/styles/non-retina_desktop_logo/s3/logo25-77x77_0.png?LzMdhn2DU4GXKEjKfJ2QYWMaQKQIk7VQ&itok=ZtYZ58tI",
iconWidth = 31*215/230,
iconHeight = 31,
iconAnchorY = 16,
iconAnchorX = 31*215/230/2)
NBA <-makeIcon(
iconUrl = "https://seeklogo.net/wp-content/uploads/2014/09/NBA-logo.png",
iconWidth = 31*215/230,
iconHeight = 31,
iconAnchorY = 16,
iconAnchorX = 31*215/230/2)
NFL <-makeIcon(
iconUrl = "https://static.nfl.com/static/content/public/static/wildcat/assets/img/application-shell/shield/default.svg",
iconWidth = 31*215/230,
iconHeight = 31,
iconAnchorY = 16,
iconAnchorX = 31*215/230/2)
I am trying to create a leaflet plot that highlights each sports team venue in my state by showing the relevant icon. The code below will only show a single icon (whichever is first in the icon = list)
df %>%
leaflet() %>%
addTiles() %>%
addMarkers(lat = df$Latitude, lng = df$Longitude, icon = c(MLB, NHL, NFL, MLS, NBA))
I've also created another data frame (df2; below) that contains each venue (Stadium Name) and the relevant league (NFL/NHL/etc) and I've tried to pass this to "icon = df2$League" but it does not recognize it as an object. Any ideas?
> colnames(df2)
[1] "Club" "Sport" "League" "Symbol" "Venue" "City" "Latitude"
[8] "Longitude"
ANSWER
Answered 2020-Apr-29 at 23:29You didn't provide reproducible data so I've made up some example data assuming your df has a column with the league name, which we can use to match the name of the icon:
library(leaflet)
library(sf)
# generate example data
set.seed(2020)
venues <- c('NHL', 'MLB', 'MLS', 'NBA', 'NFL')
nc <- st_read(system.file("shape/nc.shp", package="sf"))
df <- st_sample(nc, 5) %>%
st_coordinates() %>%
as.data.frame
df$league <- venues
df
#> X Y league
#> 1 -78.58785 35.94350 NHL
#> 2 -80.82830 35.88732 MLB
#> 3 -78.83967 36.11236 MLS
#> 4 -80.09532 35.01562 NBA
#> 5 -83.72636 35.33204 NFL
All we need to do is create a named iconList
where the name of the icon matches the name in the "league" column of our dataframe. With ~iconSet[league]
we can ensure the correct icon is being used for each point in the df.
# create iconSet
iconSet <- iconList(NHL= NHL,
MLB =MLB,
MLS = MLS,
NBA = NBA,
NFL = NFL)
# map
leaflet(df) %>%
addTiles() %>%
addMarkers(lng=~X, lat=~Y, icon = ~iconSet[league])
QUESTION
I have created a MapView in which i plot the multiple markers using longitude and latitude calling from Database.
Now, I want show bottomsheet while click on this markers and show specific data on sheet. I taken some references for bottomsheet from here Slide in view from bottom over Google Map on Marker click
but after implementing this article i get an error
error is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: part.time.job.v2, PID: 4236
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomsheet.BottomSheetBehavior.setPeekHeight(int)' on a null object reference
at part.time.job.v2.LabourFragment.onCreateView(LabourFragment.java:115)
this is my JAVA code
package part.time.job.v2;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.PlaceLikelihood;
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.maps.android.ui.IconGenerator;
import java.util.Arrays;
import java.util.List;
import model.Jobpost;
import static com.android.volley.VolleyLog.TAG;
/**
* A simple {@link Fragment} subclass.
*/
public class LabourFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapview;
private int STORAGE_PERMISSION_CODE = 1;
private CameraPosition mCameraPosition;
private FusedLocationProviderClient mFusedLocationProviderClient;
private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
private Location mLastKnownLocation;
Dialog myDialog;
private BottomSheetBehavior bottomSheetBehavior;
private View bottomSheet;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// Used for selecting the current place.
private static final int M_MAX_ENTRIES = 5;
private String[] mLikelyPlaceNames;
private String[] mLikelyPlaceAddresses;
private List[] mLikelyPlaceAttributions;
private LatLng[] mLikelyPlaceLatLngs;
private PlacesClient mPlacesClient;
public LabourFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_labour, container, false);
// myDialog = new Dialog(getActivity());
bottomSheet = view.findViewById(R.id.bottom_sheet);
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); //error occur on this line
bottomSheetBehavior.setPeekHeight(200);
bottomSheetBehavior.setHideable(true);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
Places.initialize(getActivity(), getString(R.string.google_maps_key));
mPlacesClient = Places.createClient(getActivity());
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (mGoogleMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mGoogleMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapview = (MapView) view.findViewById(R.id.mapView);
if (mMapview!=null){
mMapview.onCreate(null);
mMapview.onResume();
mMapview.getMapAsync(this);
}
}
@Override
public void onMapReady(final GoogleMap googleMap) {
mGoogleMap=googleMap;
FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
CollectionReference mOrderRef = mDatabase.collection("Job Post1");
mOrderRef.get().addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
if(documentSnapshot.contains("lat") && documentSnapshot.contains("lon")) {
String lat = (String) documentSnapshot.get("lat");
String lon = (String) documentSnapshot.get("lon");
final String title = (String) documentSnapshot.get("title");
final String jobdate = (String) documentSnapshot.get("jobdate");
final String time = (String) documentSnapshot.get("time");
if(lat != null && lon != null && !lat.isEmpty() && !lon.isEmpty()) {
double latitude = Double.parseDouble(lat.trim());
double longitude = Double.parseDouble(lon.trim());
IconGenerator iconGen = new IconGenerator(getActivity());
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromBitmap(iconGen.makeIcon(title))));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 18.0f));
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
updateBottomSheetContent(marker);
return false;
}
});
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
}
}
}
}
});
}
private void updateBottomSheetContent(Marker marker) {
TextView name = (TextView) bottomSheet.findViewById(R.id.detail_name);
name.setText(marker.getTitle());
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
xml view
bottom_sheet xml
ANSWER
Answered 2020-Feb-25 at 06:14There have no view in your xml having "R.id.bottom_sheet" id, but you are trying to get the view by findViewbyId(), thats why bottomSheet variable is having null value also the bottomsheetbehaviour value is null and producing null pointer exception when trying to access any method on it. In your case the following line:
bottomSheetBehavior.setPeekHeight(200);
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install makeicon
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page