将标记覆盖到Google静态地图图像上

时间:2016-08-24 10:56:59

标签: php google-maps google-static-maps mercator

我的任务是将自定义标记叠加到我使用Google Static Maps API生成的地图图像上。

问题在于叠加的标记总是偏离其原始位置,或者准确地说它们的位置看起来像镜像反射。

我读到了如何使用墨卡托投影从球坐标转换为笛卡尔坐标,但有些错误,我不知道是什么。

这是我的PHP代码:

class GoogleMaps
{
 const TILE_SIZE = 256;
 const MAP_IMAGE_SIZE = 640;

private function getMercatorProjection($zoomLevel, $lat, $lng)
{
    $pixelGlobeSize = self::TILE_SIZE * pow(2, $zoomLevel);
    $xPixelsToDegreesRatio = $pixelGlobeSize / 360;
    $yPixelsToRadiansRatio = $pixelGlobeSize / (2 * M_PI);
    $halfPixelGlobeSize = $pixelGlobeSize / 2;

    // get x value
    $x = ($lng + 180) * ($pixelGlobeSize/360);

    // convert from degrees to radians
    $latRad = $lat * M_PI / 180;

    // get y value
    $mercN = log(tan((M_PI / 4) + ($latRad/2)));

    $y  = ($halfPixelGlobeSize) -($pixelGlobeSize * $mercN / (2 * M_PI));

    return ['x' => $x, 'y' => $y];
}

/**
 * @return string
 */
private function getStaticMapsUrl()
{
    $url = 'http://maps.googleapis.com/maps/api/staticmap?key=' .
        env('GOOGLE_MAPS_API_KEY');

    $url .= sprintf('&path=color:%s|weight:%d|',
        env('GM_PATH_COLOR'), env('GM_PATH_WEIGHT'));

    foreach ($this->points as $point) {
        $url .= $point->lat . ',' . $point->lng . '|';
    }

    $url = rtrim($url, '|');
    $url .= '&scale=1&size=' . self::MAP_IMAGE_SIZE .
        'x' . self::MAP_IMAGE_SIZE

    $url .= '&center=' . $this->getMapCenter(true);
    $url .= '&zoom=' . ($this->getMapZoom());

    return $url;
}

private function combineMapImageWithMarker($mapImage, $marker)
{
    $resDir = realpath(__DIR__ . '/../../resources');
    $markerImgRes = imagecreatefrompng("$resDir/icons/marker.png");
    $mapImageRes = imagecreatefrompng($mapImage);

    $zoom = $this->getMapZoom();

    $mapCenter = $this->getMapCenter();
    $markerXY = $this->getMercatorProjection($zoom, $marker->lat, $marker->lng);        
    $mapCenterXY = $this->getMercatorProjection($zoom, $mapCenter['lat'], $mapCenter['lng']);

    $imageX = floor((self::MAP_IMAGE_SIZE / 2) + $mapCenterXY['x'] - $markerXY['x']);
    $imageY = floor((self::MAP_IMAGE_SIZE / 2) + $mapCenterXY['y'] - $markerXY['y']);

    imagecopy($mapImageRes, $markerImgRes,
        $imageX, $imageY,
        0, 0, $markerW, $markerH);
}

}

这就是它在地图上的样子:

enter image description here

这就是我得到的:

enter image description here

如果有任何帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用(最多5个唯一身份)custom icons in markers

IMO,在已经渲染的地图上叠加图标会让人头疼。