Had an issue where I needed to place a marker at the exact centre of my map screen and looked at a lot of questions and answers that were not exactly what I wanted to do. The app allows the user to move map about and then once crosshairs that are exactly in the centre of the map are at the desired location, you tap a button and a marker appears at that location.
map.getProjection().fromScreenLocation almost met my needs but I did not have the coordinates so could not implement that solution.
So my answer hopefully will help someone in the same situation.
So my soltuion was to use the getCameraPosition method as follows. And its fired from the button R.id.addMarker in my xml.
findViewById(R.id.addMarker).setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view) {
if(myMap != null){
double myLat = myMap.getCameraPosition().target.latitude;
double myLng = myMap.getCameraPosition().target.longitude;
LatLng markerPoint = new LatLng(myLat, myLng);
myMap.addMarker(new MarkerOptions().position(markerPoint)).setTitle("next marker");
}
}
}
);
Hope it helps someone in the same predicament.
I don't understand why fromScreenLocation doesn't suit your needs...
If you pass the map's width and the map's height divided by two as it's parameters, this function will return you a LatLng object giving you the corresponding location in terms of latitude and longitude. After that, it is easy to place a Markerat this position.
Related
Im working with OSMDroid to make map offline in Android Studio.
this is my code to create Polygon :
polygon = new Polygon();
polygon.setPoints(list_polygon);
polygon.setFillColor(Color.parseColor("#1D566E"));
polygon.setTitle(name_map);
polygon.getOutlinePaint().setColor(polygon.getFillPaint().getColor());
map.getOverlays().add(polygon);
this code is to create line :
line = new Polyline();
line.setPoints(list_line);
line.setGeodesic(true);
line.setColor(Color.parseColor("#E33E5A"));
line.getOutlinePaint().setStrokeWidth(30f);
line.setWidth(15f);
line.getPaint().setStrokeCap(Paint.Cap.ROUND);
map.getOverlays().add(line);
and this code is to get my location :
myLocation = new MyLocationNewOverlay(map);
myLocation.enableFollowLocation();
myLocation.setDirectionArrow(icTruk, icTruk);
myLocation.enableMyLocation();
myLocation.setDrawAccuracyEnabled(true);
map.getOverlays().add(myLocation);
I have done to create polygon and polyline in osmdroid.
But now i want read that polygon or polyline if mylocation inthere ?
How to make it posible ?
You could do the following to get the current location and then check if it is close to the Polyline.
MyLocationNewOverlay myLocation= new MyLocationNewOverlay(mapView) {
#Override
public void onLocationChanged(Location location, IMyLocationProvider source) {
super.onLocationChanger(location, source);
// Turn the current location into a GeoPoint
GeoPoint currentPoint = new GeoPoint(location.getLatitude(), location.getLongitude);
// Set tolerance for isCloseTo
// Might need to play around with this value
// and see which fits best for your needs
double tolerance = 5.0;
// Check if location is close to Polyline
if (line.isCloseTo(currentPoint, tolerance, map)) {
// Do here what you want to do,
// when location is close to Polyline
}
}
}
Checking, if the location/GeoPoint is within a given polygon is a bit more work, since the only integrated method for that is based on MotionEvent rather than GeoPoint and only returns a correct value in a very specific scenario, see this for reference. But there are some answers out there, which might be usable for your need, like this one.
References:
Get the current location
OSMDroid Geopoint class
Android Location class
OSMDroid Polyline.isCloseTo
OSMDroid Polygon.contains
One way to check if point is in a polygon
I need to convert coordinates X, Y into Latitude and Longitude. I've read wikipedia map projections, similar stackoverflow forums, applied my custom solutions and still didn't work.
The coordinates I get from my formula are wrong, Longitude is acceptable but Latitude is not. I don't see where my calculous is wrong.
The X,Y Point is taken from a JLayeredPane with the size of a background Map image, once a smaller image is released on this Map image, the point is taken.
public void mouseReleased(MouseEvent e) {
DM.setUpCoordinates(layeredPane.getComponent(index-1).getLocation());
}
After this, I'm trying to correctly calculate the Latitude and Longitude projection. The data I own is:
X,Y coordinates from the Map
Total width and height from the Map
Latitude and Longitude where the map is centered
What I have tryied so far:
Trying Equirectangular projection
public void setUpCoordinates(Point p) {
//Equirectangular projection: optimal for small streets
Long = ((p.getX())/(6371000*Math.cos(MG.getLati())))+MG.getLongi();
Lat = (((p.getY())/6371000)+MG.getLati());
}
I also tryied to implement the Mercator projection from this link with very little to no success at all.
I am aware I'm not using total width and height from the Map on my formulas and this might be the error, but I don't know how to use it!
any help how to convert from (x,y) to (latitude, longitude)?
Thanks,
You need to shift pixel coordinates by center position and also use map scale - longitude and latitude range (I assume that elongation Math.cos(MG.getLati()) coefficient is accounted in longitude scale)
Long = (p.getX() - MapWidth/2)*LongitudeRange/MapWidth +MG.getLongi();
Lat = (p.getY() - MapHeight/2)*LatitudeRange/MapHeight + MG.getLati());
I have followed a 24 hours textbook and created an Android app that is supposed to launch Google maps and navigate to a specific location based on latitude and longitude coordinates hard coded into the app. However, when I launch the app and run the code it opens Google maps or Google Earth and always defaults to my current location. How do I prevent it from doing this?
I am trying to get my app to go to a specific latitude and longitude, but when it launches Google Maps or Google Earth it always defaults to my current location. Java Code is as follows:
Button mapButton = (Button) findViewById(R.id.button2);
mapButton.setOnClickListener(new View.OnClickListener() {
#override
public void onClick(View view) {
String geoURI = "geo:37.422,-122.0847z=23";
Uri geo = Uri.parse(geoURI);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, geo);
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
How do I get it to override the default location and go to the coordinates I have hard coded above?
Looking at the documentation, the line:
String geoURI = "geo:37.422,-122.0847z=23";
Appears to be invalid syntax, but might be wanting to zoom. Try:
String geoURI = "geo:37.422,-122.0847?z=23";
Zoom level only goes up to 21, however, so also try:
String geoURI = "geo:37.422,-122.0847?z=21";
If neither work, use a basic string without any zoom:
String geoURI = "geo:37.422,-122.0847";
Try this:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:<lat>,<long>?q=<lat>,<long>(Label+Name)"));
startActivity(intent);
You can omit (Label+Name) if you don't want a label, and it will choose one randomly based on the nearest street or other thing it thinks relevant.
You can create LatLng object and tell google map to load the location. Code to do that will be something like this:
double lat=26.52719;
double lng=88.72448;
LatLng myLocation = new LatLng(lat,lng);
if(this.googleMap !=null){
this.googleMap.addMarker(new MarkerOptions().position(myLocation).title("Your current Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
}
Remember you should apply this in onMapReady callback and to turn off your current location placing in google map you can do
this.googleMap.setMyLocationEnabled(true);
I implemented the speedometer in my project by referring the code as found in the below link.
I need to animate the speedometer needle till i get the result from server, and once i got the result , i need to set the needle to proper value based on some calculation.
I am not understanding how to do it.
Please help me with some solution.
https://github.com/ntoskrnl/SpeedometerView/blob/master/CardioMoodSpeedometerView/SpeedometerView/src/main/java/com/cardiomood/android/speedometer/SpeedometerView.java
private SpeedometerView speedometer;
// Customize SpeedometerView
speedometer = (SpeedometerView) v.findViewById(R.id.speedometer);
// Add label converter
speedometer.setLabelConverter(new SpeedometerView.LabelConverter() {
#Override
public String getLabelFor(double progress, double maxProgress) {
return String.valueOf((int) Math.round(progress));
}
});
// configure value range and ticks
speedometer.setMaxSpeed(300);
speedometer.setMajorTickStep(30);
speedometer.setMinorTicks(2);
// Configure value range colors
speedometer.addColoredRange(30, 140, Color.GREEN);
speedometer.addColoredRange(140, 180, Color.YELLOW);
speedometer.addColoredRange(180, 400, Color.RED);
Check the readme. Here you will find above code. And i think you need to look for how to change the needle.
And then call the public method SetSpeed(double speed) on the speedometer object.
A simple look through the code in your link provides the answer.
We are using JFreeChart to make XY plots and we have a feature request to do a crosshair that moves along with the mouse and highlights the data point that most closely maps to the x-value of the mouse. You can see a similar example at Google Finance - http://www.google.com/finance?q=INDEXDJX:.DJI,INDEXSP:.INX,INDEXNASDAQ:.IXIC.
Those Google charts only highlight the current value (we want to do that and also show crosshairs), but they show the live mouse interaction we are looking for.
Anyone have any elegant suggestions?
Thanks.
I got this working using a mouse listener and the CrosshairOverlay class. After I get back from holiday travel, I will post my code. It ended up being not too difficult.
Sorry, I forgot about this!
First, you want to calculate the x, y values for where you want your crosshair. For me, I wanted it to move along the points of our line, so I calculated the closest x value and used that data pair for x, y.
Then I call this method:
protected void setCrosshairLocation(double x, Double y) {
Crosshair domainCrosshair;
List domainCrosshairs = crosshairOverlay.getDomainCrosshairs();
if (domainCrosshairs.isEmpty()) {
domainCrosshair = new Crosshair();
domainCrosshair.setPaint(BlueStripeColors.LIGHT_GRAY_C0);
crosshairOverlay.addDomainCrosshair(domainCrosshair);
}
else {
// We only have one at a time
domainCrosshair = (Crosshair) domainCrosshairs.get(0);
}
domainCrosshair.setValue(x);
if (y != null) {
Crosshair rangeCrosshair;
List rangeCrosshairs = crosshairOverlay.getRangeCrosshairs();
if (rangeCrosshairs.isEmpty()) {
rangeCrosshair = new Crosshair();
rangeCrosshair.setPaint(BlueStripeColors.LIGHT_GRAY_C0);
crosshairOverlay.addRangeCrosshair(rangeCrosshair);
}
else {
// We only have one at a time
rangeCrosshair = (Crosshair) rangeCrosshairs.get(0);
}
rangeCrosshair.setValue(y);
}
}
Note that crosshairOverlay is an instance of CrosshairOverlay.
JFreeChart can't render a sub-section of a chart, so you'll want to do something that doesn't require repainting the chart. You could write your chart to a BufferedImage and store that in memory, then have a custom component which uses the buffered chart as the background image, and draws crosshairs and other popup windows over it.
There are methods in JFreeChart to get the data point for a given coordinate on a rendered chart. Don't recall what these are off the top of my head. Depending on your needs, you might consider rendering your own chart data, it's not as hard as you'd think.
The first thing that comes to my mind would be to write a custom Cursor and set it on your chart. It can have a reference to the chart and highlight the x value that's consistent with the Cursor's x/y location.
This worked for me. I set the
chartPanel.addChartMouseListener(new ChartMouseListener() {
public void chartMouseMoved(ChartMouseEvent event)
{
try
{
double[] values = getCrossHairValue(event);
plot.clearRangeMarkers();
plot.clearDomainMarkers();
Marker yMarker = new ValueMarker(values[1]);
yMarker.setPaint(Color.darkGray);
plot.addRangeMarker(yMarker);
Marker xMarker = new ValueMarker(values[0]);
xMarker.setPaint(Color.darkGray);
plot.addDomainMarker(xMarker);
chartPanel.repaint();
} catch (Exception e)
{
}
}
}