MKMapRectMake как уменьшить после настройки
Я использую MKMapRectMake
отметить северо-восток и юго-запад, чтобы отобразить регион. Вот как я это делаю:
routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y);
[self.mapView setVisibleMapRect:routeRect];
После того, как я настроил эту область отображения, как я могу немного уменьшить карту? Каков наилучший способ сделать это?
ОБНОВИТЬ
Это код, который я использую, чтобы получить rect
за setVisibleMapRect
функция:
for(Path* p in ar)
{
self.routeLine = nil;
self.routeLineView = nil;
// while we create the route points, we will also be calculating the bounding box of our route
// so we can easily zoom in on it.
MKMapPoint northEastPoint;
MKMapPoint southWestPoint;
// create a c array of points.
MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * ar.count);
for(int idx = 0; idx < ar.count; idx++)
{
Path *m_p = [ar objectAtIndex:idx];
[NSCharacterSet characterSetWithCharactersInString:@","]];
CLLocationDegrees latitude = m_p.Latitude;
CLLocationDegrees longitude = m_p.Longitude;
// create our coordinate and add it to the correct spot in the array
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
MKMapPoint point = MKMapPointForCoordinate(coordinate);
// adjust the bounding box
// if it is the first point, just use them, since we have nothing to compare to yet.
if (idx == 0) {
northEastPoint = point;
southWestPoint = point;
}
else
{
if (point.x > northEastPoint.x)
northEastPoint.x = point.x;
if(point.y > northEastPoint.y)
northEastPoint.y = point.y;
if (point.x < southWestPoint.x)
southWestPoint.x = point.x;
if (point.y < southWestPoint.y)
southWestPoint.y = point.y;
}
pointArr[idx] = point;
}
// create the polyline based on the array of points.
self.routeLine = [MKPolyline polylineWithPoints:pointArr count:ar.count];
_routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y);
// clear the memory allocated earlier for the points
free(pointArr);
[self.mapView removeOverlays: self.mapView.overlays];
// add the overlay to the map
if (nil != self.routeLine) {
[self.mapView addOverlay:self.routeLine];
}
// zoom in on the route.
[self zoomInOnRoute];
}
4 ответа
Попробуйте это: (Изменить)
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
CLLocationCoordinate2D zoomLocation = newLocation.coordinate;
region.center = zoomLocation;
region.span = span;
region = [mapViewObject regionThatFits:region];
[mapViewObject setRegion:region animated:NO];
Вы можете использовать эту пользовательскую функцию, чтобы центрировать карту вокруг двух точек.
- (void)centerMapAroundSourceAndDestination
{
MKMapRect rect = MKMapRectNull;
MKMapPoint sourcePoint = MKMapPointForCoordinate(southWestPoint);
rect = MKMapRectUnion(rect, MKMapRectMake(sourcePoint.x, sourcePoint.y, 0, 0));
MKMapPoint destinationPoint = MKMapPointForCoordinate(_northEastPoint);
rect= MKMapRectUnion(rect, MKMapRectMake(destinationPoint.x, destinationPoint.y, 0, 0));
MKCoordinateRegion region = MKCoordinateRegionForMapRect(rect);
[_mapView setRegion:region animated:YES];
}
Таким образом, в этом случае вам нужно найти Centroid многоугольника и затем передать значения этого центроида этому методу, чтобы он масштабировался до центра многоугольника, то есть Centroid.
- (void)zoomMapView:(MKMapView *)mapview withLatitude:(Float32 )latitude andLongitude:(Float32 )longitude {
MKCoordinateRegion region;
region.span.latitudeDelta =0.005; //Change values to zoom. lower the value to zoom in and vice-versa
region.span.longitudeDelta = 0.009;//Change values to zoom. lower the value to zoom in and vice-versa
CLLocationCoordinate2D location;
location.latitude = latitude; // Add your Current Latitude here.
location.longitude = longitude; // Add your Current Longitude here.
region.center = location;
[mapview setRegion:region];
}
Чтобы использовать этот метод, вам нужно передать три вещи mapView, широту и долготу, т. Е. Position, где увеличить.
как я могу немного уменьшить карту?
Unfortunatley MkMapView
setRegion ведет себя так странно, что это не работает на iPhone. (ios 6.1.3) работает на iPad (ios 6.1.3)
setRegion
а также setVisibleMapRect
оба изменяют коэффициент увеличения только с шагом в два. Таким образом, вы не можете программно уменьшить масштаб, например, на 10%. Несмотря на то, что карты Apple основаны на векторах, они все же фиксируют следующий более высокий уровень масштабирования, который (будет) соответствовать пикселям фрагмента карты 1:1. Может быть, чтобы быть совместимым с режимом отображения спутниковой карты, который использует предварительно обработанные растровые изображения.
Хотя бот-методы должны корректировать соотношение сторон только в том случае, если вы предоставили один из диапазонов широты / долготы не идеально, они дополнительно привязываются к указанным уровням масштабирования.
Попробуйте: отобразите карту, затем нажмите кнопку: получите текущую область, увеличьте интервал долготы на 10% (коэффициент 1.1), установите регион, затем прочитайте его обратно, вы увидите на iphone simu и на устройстве iphone4 долготу span теперь вдвое больше, чем коэффициент 1.1.
До сегодняшнего дня не существует хорошего решения.
Позор тебе, Apple.