How do i add nearest markers in google maps programmatically through json data











up vote
0
down vote

favorite












I am fairly new to stack and Android and in need of some help adding nearest markers through android code with JSON data, the lat and lon come through in the JSON. I have the store info displaying on the page I just do not know how to add markers to the map. Any help would be appreciated

my code is below:



package com.example.mdona.maptest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.renderscript.Double3;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.google.android.gms.maps.MapFragment;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static java.lang.Double.valueOf;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private static JsonNinja jninja = new JsonNinja();
private static String API_KEY ="MDpmNWI1YTdkYS1lNDNhLTExZTgtOTE1Yy02ZjczZWQ0ZmIxM2M6dkJad1htQW56TUtNMWRDSzJISjZoVjU3bzFRNE9GREdHT1ZK";
private ArrayList<String> address_final = new ArrayList<>();
private ArrayList<String> storeLat = new ArrayList<>();
private ArrayList<String> storeLon = new ArrayList<>();
private ArrayList<String> city = new ArrayList<>();
private ArrayList<String> telephone = new ArrayList<>();
private ArrayList<String> quantity = new ArrayList<>();
String product_id;
double latitude;
double longitude;

LinearLayout NearestLocation;

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);

NearestLocation = findViewById(R.id.nearest_location);
}

@Override
public void onPause() {
super.onPause();

if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000);
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
else {
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}

LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
Location location = locationList.get(locationList.size() - 1);

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

getLatitude();
getLongitude();
getUserStoreLocInv("311787", latitude, longitude);

mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
}
};

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}

} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}

public double getLatitude() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
}
return latitude;
}

public double getLongitude() {
if (mLastLocation != null) {
longitude = mLastLocation.getLongitude();
}
return longitude;
}

public void getUserStoreLocInv(String product_id, double lat, double lon) {

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", API_KEY);
client.addHeader("Accept", "application/json");

client.get("http://lcboapi.com/stores?lat=" + lat + "&lon=" + lon + "&product_id=" + product_id + "&per_page=5", new AsyncHttpResponseHandler() {
//====================================>>
//=========== SUCCESS =============>>
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody) {
Log.e("Success", "Yes!");

String converted_string = new String(responseBody);
jninja.NinjaParse(converted_string);

ArrayList<String> names = jninja.GetNames();
ArrayList<String> vals = jninja.GetVals();

for (int i = 0; i < vals.size(); i++) {
if (names.get(i).equals("address_line_1")) {
address_final.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("city")) {
city.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("telephone")) {
telephone.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("quantity")) {
quantity.add(vals.get(i));
}
if (names.get(i).equals("latitude")) {
storeLat.add(vals.get(i));
}
if (names.get(i).equals("longitude")) {
storeLon.add(vals.get(i));
}
}
CreateStoreAddress(address_final, city, telephone, quantity);
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody, Throwable error) {
Log.e("Fail", "No!");
}
});
}
public void CreateStoreAddress(ArrayList<String> address_final, ArrayList<String> city, ArrayList<String> telephone,
ArrayList<String> quantity)
{
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;

for (int i = 0; i < address_final.size(); i++) {

LinearLayout addressCompleteLayout = new LinearLayout(this);
LinearLayout addressLayout = new LinearLayout(this);
LinearLayout cityLayout = new LinearLayout(this);
LinearLayout telephoneLayout = new LinearLayout(this);
LinearLayout quantityLayout = new LinearLayout(this);

GradientDrawable border = new GradientDrawable();
border.setStroke(3, Color.BLACK);
border.setSize(screenWidth, 100);

TextView address = new TextView(this);
TextView city_loc = new TextView(this);
TextView phone = new TextView(this);
TextView amount = new TextView(this);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(20,20,20,20);

addressCompleteLayout.setLayoutParams(params);
addressCompleteLayout.setOrientation(LinearLayout.VERTICAL);
addressCompleteLayout.setBackground(border);
NearestLocation.addView(addressCompleteLayout);

addressLayout.setLayoutParams(params);
addressLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(addressLayout);

cityLayout.setLayoutParams(params);
cityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(cityLayout);

telephoneLayout.setLayoutParams(params);
telephoneLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(telephoneLayout);

quantityLayout.setLayoutParams(params);
quantityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(quantityLayout);

address.setLayoutParams(params);
address.setText("Address: " + address_final.get(i));
addressLayout.addView(address);

city_loc.setLayoutParams(params);
city_loc.setText("City: " + city.get(i));
cityLayout.addView(city_loc);

amount.setLayoutParams(params);
amount.setText("Quantity Available: " + quantity.get(i));
quantityLayout.addView(amount);

phone.setLayoutParams(params);
phone.setText("Phone #: " + telephone.get(i));
telephoneLayout.addView(phone);
}
}
}









share|improve this question
























  • That is a lot of code with no explanation...
    – f1sh
    Nov 22 at 15:24










  • Yes. It would be better if you were to take out all the imports and explain the purpose of your code. It is a lot of code to read and understand.
    – Ishaan
    Nov 22 at 15:27










  • Basically, people are asking for a Minimal, Complete, and Verifiable example that describes your attempt.
    – jdv
    Nov 22 at 16:45















up vote
0
down vote

favorite












I am fairly new to stack and Android and in need of some help adding nearest markers through android code with JSON data, the lat and lon come through in the JSON. I have the store info displaying on the page I just do not know how to add markers to the map. Any help would be appreciated

my code is below:



package com.example.mdona.maptest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.renderscript.Double3;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.google.android.gms.maps.MapFragment;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static java.lang.Double.valueOf;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private static JsonNinja jninja = new JsonNinja();
private static String API_KEY ="MDpmNWI1YTdkYS1lNDNhLTExZTgtOTE1Yy02ZjczZWQ0ZmIxM2M6dkJad1htQW56TUtNMWRDSzJISjZoVjU3bzFRNE9GREdHT1ZK";
private ArrayList<String> address_final = new ArrayList<>();
private ArrayList<String> storeLat = new ArrayList<>();
private ArrayList<String> storeLon = new ArrayList<>();
private ArrayList<String> city = new ArrayList<>();
private ArrayList<String> telephone = new ArrayList<>();
private ArrayList<String> quantity = new ArrayList<>();
String product_id;
double latitude;
double longitude;

LinearLayout NearestLocation;

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);

NearestLocation = findViewById(R.id.nearest_location);
}

@Override
public void onPause() {
super.onPause();

if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000);
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
else {
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}

LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
Location location = locationList.get(locationList.size() - 1);

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

getLatitude();
getLongitude();
getUserStoreLocInv("311787", latitude, longitude);

mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
}
};

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}

} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}

public double getLatitude() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
}
return latitude;
}

public double getLongitude() {
if (mLastLocation != null) {
longitude = mLastLocation.getLongitude();
}
return longitude;
}

public void getUserStoreLocInv(String product_id, double lat, double lon) {

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", API_KEY);
client.addHeader("Accept", "application/json");

client.get("http://lcboapi.com/stores?lat=" + lat + "&lon=" + lon + "&product_id=" + product_id + "&per_page=5", new AsyncHttpResponseHandler() {
//====================================>>
//=========== SUCCESS =============>>
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody) {
Log.e("Success", "Yes!");

String converted_string = new String(responseBody);
jninja.NinjaParse(converted_string);

ArrayList<String> names = jninja.GetNames();
ArrayList<String> vals = jninja.GetVals();

for (int i = 0; i < vals.size(); i++) {
if (names.get(i).equals("address_line_1")) {
address_final.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("city")) {
city.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("telephone")) {
telephone.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("quantity")) {
quantity.add(vals.get(i));
}
if (names.get(i).equals("latitude")) {
storeLat.add(vals.get(i));
}
if (names.get(i).equals("longitude")) {
storeLon.add(vals.get(i));
}
}
CreateStoreAddress(address_final, city, telephone, quantity);
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody, Throwable error) {
Log.e("Fail", "No!");
}
});
}
public void CreateStoreAddress(ArrayList<String> address_final, ArrayList<String> city, ArrayList<String> telephone,
ArrayList<String> quantity)
{
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;

for (int i = 0; i < address_final.size(); i++) {

LinearLayout addressCompleteLayout = new LinearLayout(this);
LinearLayout addressLayout = new LinearLayout(this);
LinearLayout cityLayout = new LinearLayout(this);
LinearLayout telephoneLayout = new LinearLayout(this);
LinearLayout quantityLayout = new LinearLayout(this);

GradientDrawable border = new GradientDrawable();
border.setStroke(3, Color.BLACK);
border.setSize(screenWidth, 100);

TextView address = new TextView(this);
TextView city_loc = new TextView(this);
TextView phone = new TextView(this);
TextView amount = new TextView(this);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(20,20,20,20);

addressCompleteLayout.setLayoutParams(params);
addressCompleteLayout.setOrientation(LinearLayout.VERTICAL);
addressCompleteLayout.setBackground(border);
NearestLocation.addView(addressCompleteLayout);

addressLayout.setLayoutParams(params);
addressLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(addressLayout);

cityLayout.setLayoutParams(params);
cityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(cityLayout);

telephoneLayout.setLayoutParams(params);
telephoneLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(telephoneLayout);

quantityLayout.setLayoutParams(params);
quantityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(quantityLayout);

address.setLayoutParams(params);
address.setText("Address: " + address_final.get(i));
addressLayout.addView(address);

city_loc.setLayoutParams(params);
city_loc.setText("City: " + city.get(i));
cityLayout.addView(city_loc);

amount.setLayoutParams(params);
amount.setText("Quantity Available: " + quantity.get(i));
quantityLayout.addView(amount);

phone.setLayoutParams(params);
phone.setText("Phone #: " + telephone.get(i));
telephoneLayout.addView(phone);
}
}
}









share|improve this question
























  • That is a lot of code with no explanation...
    – f1sh
    Nov 22 at 15:24










  • Yes. It would be better if you were to take out all the imports and explain the purpose of your code. It is a lot of code to read and understand.
    – Ishaan
    Nov 22 at 15:27










  • Basically, people are asking for a Minimal, Complete, and Verifiable example that describes your attempt.
    – jdv
    Nov 22 at 16:45













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am fairly new to stack and Android and in need of some help adding nearest markers through android code with JSON data, the lat and lon come through in the JSON. I have the store info displaying on the page I just do not know how to add markers to the map. Any help would be appreciated

my code is below:



package com.example.mdona.maptest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.renderscript.Double3;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.google.android.gms.maps.MapFragment;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static java.lang.Double.valueOf;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private static JsonNinja jninja = new JsonNinja();
private static String API_KEY ="MDpmNWI1YTdkYS1lNDNhLTExZTgtOTE1Yy02ZjczZWQ0ZmIxM2M6dkJad1htQW56TUtNMWRDSzJISjZoVjU3bzFRNE9GREdHT1ZK";
private ArrayList<String> address_final = new ArrayList<>();
private ArrayList<String> storeLat = new ArrayList<>();
private ArrayList<String> storeLon = new ArrayList<>();
private ArrayList<String> city = new ArrayList<>();
private ArrayList<String> telephone = new ArrayList<>();
private ArrayList<String> quantity = new ArrayList<>();
String product_id;
double latitude;
double longitude;

LinearLayout NearestLocation;

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);

NearestLocation = findViewById(R.id.nearest_location);
}

@Override
public void onPause() {
super.onPause();

if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000);
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
else {
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}

LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
Location location = locationList.get(locationList.size() - 1);

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

getLatitude();
getLongitude();
getUserStoreLocInv("311787", latitude, longitude);

mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
}
};

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}

} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}

public double getLatitude() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
}
return latitude;
}

public double getLongitude() {
if (mLastLocation != null) {
longitude = mLastLocation.getLongitude();
}
return longitude;
}

public void getUserStoreLocInv(String product_id, double lat, double lon) {

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", API_KEY);
client.addHeader("Accept", "application/json");

client.get("http://lcboapi.com/stores?lat=" + lat + "&lon=" + lon + "&product_id=" + product_id + "&per_page=5", new AsyncHttpResponseHandler() {
//====================================>>
//=========== SUCCESS =============>>
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody) {
Log.e("Success", "Yes!");

String converted_string = new String(responseBody);
jninja.NinjaParse(converted_string);

ArrayList<String> names = jninja.GetNames();
ArrayList<String> vals = jninja.GetVals();

for (int i = 0; i < vals.size(); i++) {
if (names.get(i).equals("address_line_1")) {
address_final.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("city")) {
city.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("telephone")) {
telephone.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("quantity")) {
quantity.add(vals.get(i));
}
if (names.get(i).equals("latitude")) {
storeLat.add(vals.get(i));
}
if (names.get(i).equals("longitude")) {
storeLon.add(vals.get(i));
}
}
CreateStoreAddress(address_final, city, telephone, quantity);
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody, Throwable error) {
Log.e("Fail", "No!");
}
});
}
public void CreateStoreAddress(ArrayList<String> address_final, ArrayList<String> city, ArrayList<String> telephone,
ArrayList<String> quantity)
{
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;

for (int i = 0; i < address_final.size(); i++) {

LinearLayout addressCompleteLayout = new LinearLayout(this);
LinearLayout addressLayout = new LinearLayout(this);
LinearLayout cityLayout = new LinearLayout(this);
LinearLayout telephoneLayout = new LinearLayout(this);
LinearLayout quantityLayout = new LinearLayout(this);

GradientDrawable border = new GradientDrawable();
border.setStroke(3, Color.BLACK);
border.setSize(screenWidth, 100);

TextView address = new TextView(this);
TextView city_loc = new TextView(this);
TextView phone = new TextView(this);
TextView amount = new TextView(this);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(20,20,20,20);

addressCompleteLayout.setLayoutParams(params);
addressCompleteLayout.setOrientation(LinearLayout.VERTICAL);
addressCompleteLayout.setBackground(border);
NearestLocation.addView(addressCompleteLayout);

addressLayout.setLayoutParams(params);
addressLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(addressLayout);

cityLayout.setLayoutParams(params);
cityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(cityLayout);

telephoneLayout.setLayoutParams(params);
telephoneLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(telephoneLayout);

quantityLayout.setLayoutParams(params);
quantityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(quantityLayout);

address.setLayoutParams(params);
address.setText("Address: " + address_final.get(i));
addressLayout.addView(address);

city_loc.setLayoutParams(params);
city_loc.setText("City: " + city.get(i));
cityLayout.addView(city_loc);

amount.setLayoutParams(params);
amount.setText("Quantity Available: " + quantity.get(i));
quantityLayout.addView(amount);

phone.setLayoutParams(params);
phone.setText("Phone #: " + telephone.get(i));
telephoneLayout.addView(phone);
}
}
}









share|improve this question















I am fairly new to stack and Android and in need of some help adding nearest markers through android code with JSON data, the lat and lon come through in the JSON. I have the store info displaying on the page I just do not know how to add markers to the map. Any help would be appreciated

my code is below:



package com.example.mdona.maptest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.renderscript.Double3;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.google.android.gms.maps.MapFragment;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static java.lang.Double.valueOf;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private static JsonNinja jninja = new JsonNinja();
private static String API_KEY ="MDpmNWI1YTdkYS1lNDNhLTExZTgtOTE1Yy02ZjczZWQ0ZmIxM2M6dkJad1htQW56TUtNMWRDSzJISjZoVjU3bzFRNE9GREdHT1ZK";
private ArrayList<String> address_final = new ArrayList<>();
private ArrayList<String> storeLat = new ArrayList<>();
private ArrayList<String> storeLon = new ArrayList<>();
private ArrayList<String> city = new ArrayList<>();
private ArrayList<String> telephone = new ArrayList<>();
private ArrayList<String> quantity = new ArrayList<>();
String product_id;
double latitude;
double longitude;

LinearLayout NearestLocation;

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);

NearestLocation = findViewById(R.id.nearest_location);
}

@Override
public void onPause() {
super.onPause();

if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000);
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
else {
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}

LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
Location location = locationList.get(locationList.size() - 1);

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

getLatitude();
getLongitude();
getUserStoreLocInv("311787", latitude, longitude);

mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
}
};

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}

} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}

public double getLatitude() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
}
return latitude;
}

public double getLongitude() {
if (mLastLocation != null) {
longitude = mLastLocation.getLongitude();
}
return longitude;
}

public void getUserStoreLocInv(String product_id, double lat, double lon) {

AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", API_KEY);
client.addHeader("Accept", "application/json");

client.get("http://lcboapi.com/stores?lat=" + lat + "&lon=" + lon + "&product_id=" + product_id + "&per_page=5", new AsyncHttpResponseHandler() {
//====================================>>
//=========== SUCCESS =============>>
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody) {
Log.e("Success", "Yes!");

String converted_string = new String(responseBody);
jninja.NinjaParse(converted_string);

ArrayList<String> names = jninja.GetNames();
ArrayList<String> vals = jninja.GetVals();

for (int i = 0; i < vals.size(); i++) {
if (names.get(i).equals("address_line_1")) {
address_final.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("city")) {
city.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("telephone")) {
telephone.add(vals.get(i).replace(""",""));
}
if (names.get(i).equals("quantity")) {
quantity.add(vals.get(i));
}
if (names.get(i).equals("latitude")) {
storeLat.add(vals.get(i));
}
if (names.get(i).equals("longitude")) {
storeLon.add(vals.get(i));
}
}
CreateStoreAddress(address_final, city, telephone, quantity);
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header headers, byte responseBody, Throwable error) {
Log.e("Fail", "No!");
}
});
}
public void CreateStoreAddress(ArrayList<String> address_final, ArrayList<String> city, ArrayList<String> telephone,
ArrayList<String> quantity)
{
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;

for (int i = 0; i < address_final.size(); i++) {

LinearLayout addressCompleteLayout = new LinearLayout(this);
LinearLayout addressLayout = new LinearLayout(this);
LinearLayout cityLayout = new LinearLayout(this);
LinearLayout telephoneLayout = new LinearLayout(this);
LinearLayout quantityLayout = new LinearLayout(this);

GradientDrawable border = new GradientDrawable();
border.setStroke(3, Color.BLACK);
border.setSize(screenWidth, 100);

TextView address = new TextView(this);
TextView city_loc = new TextView(this);
TextView phone = new TextView(this);
TextView amount = new TextView(this);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(20,20,20,20);

addressCompleteLayout.setLayoutParams(params);
addressCompleteLayout.setOrientation(LinearLayout.VERTICAL);
addressCompleteLayout.setBackground(border);
NearestLocation.addView(addressCompleteLayout);

addressLayout.setLayoutParams(params);
addressLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(addressLayout);

cityLayout.setLayoutParams(params);
cityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(cityLayout);

telephoneLayout.setLayoutParams(params);
telephoneLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(telephoneLayout);

quantityLayout.setLayoutParams(params);
quantityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(quantityLayout);

address.setLayoutParams(params);
address.setText("Address: " + address_final.get(i));
addressLayout.addView(address);

city_loc.setLayoutParams(params);
city_loc.setText("City: " + city.get(i));
cityLayout.addView(city_loc);

amount.setLayoutParams(params);
amount.setText("Quantity Available: " + quantity.get(i));
quantityLayout.addView(amount);

phone.setLayoutParams(params);
phone.setText("Phone #: " + telephone.get(i));
telephoneLayout.addView(phone);
}
}
}






java android






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 16:57









Skynet

4,27452640




4,27452640










asked Nov 22 at 15:21









Mike Donati

32




32












  • That is a lot of code with no explanation...
    – f1sh
    Nov 22 at 15:24










  • Yes. It would be better if you were to take out all the imports and explain the purpose of your code. It is a lot of code to read and understand.
    – Ishaan
    Nov 22 at 15:27










  • Basically, people are asking for a Minimal, Complete, and Verifiable example that describes your attempt.
    – jdv
    Nov 22 at 16:45


















  • That is a lot of code with no explanation...
    – f1sh
    Nov 22 at 15:24










  • Yes. It would be better if you were to take out all the imports and explain the purpose of your code. It is a lot of code to read and understand.
    – Ishaan
    Nov 22 at 15:27










  • Basically, people are asking for a Minimal, Complete, and Verifiable example that describes your attempt.
    – jdv
    Nov 22 at 16:45
















That is a lot of code with no explanation...
– f1sh
Nov 22 at 15:24




That is a lot of code with no explanation...
– f1sh
Nov 22 at 15:24












Yes. It would be better if you were to take out all the imports and explain the purpose of your code. It is a lot of code to read and understand.
– Ishaan
Nov 22 at 15:27




Yes. It would be better if you were to take out all the imports and explain the purpose of your code. It is a lot of code to read and understand.
– Ishaan
Nov 22 at 15:27












Basically, people are asking for a Minimal, Complete, and Verifiable example that describes your attempt.
– jdv
Nov 22 at 16:45




Basically, people are asking for a Minimal, Complete, and Verifiable example that describes your attempt.
– jdv
Nov 22 at 16:45












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










So what you would do to create a marker is add the following to onMapReady:



final LatLng coordinates= new LatLng(35, 35);
Marker Options myMarker= new MarkerOptions().position(coordinates).title("Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mGoogleMap.addMarker(myMarker);


This adds a marker on your map. Now, what you can do is replace the 35 with the coordinates from your json file. I hope this answers your question.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434032%2fhow-do-i-add-nearest-markers-in-google-maps-programmatically-through-json-data%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    So what you would do to create a marker is add the following to onMapReady:



    final LatLng coordinates= new LatLng(35, 35);
    Marker Options myMarker= new MarkerOptions().position(coordinates).title("Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
    mGoogleMap.addMarker(myMarker);


    This adds a marker on your map. Now, what you can do is replace the 35 with the coordinates from your json file. I hope this answers your question.






    share|improve this answer

























      up vote
      0
      down vote



      accepted










      So what you would do to create a marker is add the following to onMapReady:



      final LatLng coordinates= new LatLng(35, 35);
      Marker Options myMarker= new MarkerOptions().position(coordinates).title("Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
      mGoogleMap.addMarker(myMarker);


      This adds a marker on your map. Now, what you can do is replace the 35 with the coordinates from your json file. I hope this answers your question.






      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        So what you would do to create a marker is add the following to onMapReady:



        final LatLng coordinates= new LatLng(35, 35);
        Marker Options myMarker= new MarkerOptions().position(coordinates).title("Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        mGoogleMap.addMarker(myMarker);


        This adds a marker on your map. Now, what you can do is replace the 35 with the coordinates from your json file. I hope this answers your question.






        share|improve this answer












        So what you would do to create a marker is add the following to onMapReady:



        final LatLng coordinates= new LatLng(35, 35);
        Marker Options myMarker= new MarkerOptions().position(coordinates).title("Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        mGoogleMap.addMarker(myMarker);


        This adds a marker on your map. Now, what you can do is replace the 35 with the coordinates from your json file. I hope this answers your question.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 15:25









        Ishaan

        7671417




        7671417






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434032%2fhow-do-i-add-nearest-markers-in-google-maps-programmatically-through-json-data%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            Alexandru Averescu

            Trompette piccolo