<?php

    $im_url 
'http://farm1.static.flickr.com/29/52139344_21e210d829.jpg';
    
$lat '37.507653';
    
$lon '-122.339994';

    
$im_data file_get_contents($im_url);

    if (! 
$im_data){
        echo 
"failed to retrieve '$im_url'";
        exit;
    }

    
$im imagecreatefromstring($im_data);
    
    if (! 
$im){
        echo 
"failed to create image from '$im_url'";
        exit;
    }

    
$im_width imagesx($im);
    
$im_height imagesy($im);
    
    
$marker_args = array('example'$lat$lon$im_width$im_height);
    
$marker_args implode(","$marker_args);
    
    
$mm_args = array(
             
'filter=' 'atkinson',
             
'provider=' 'MICROSOFT_AERIAL',
             
'method=' 'center',
             
'latitude=' urlencode($lat),
             
'longitude=' urlencode($lon),
             
'zoom=' 17,
             
'height=' 1239,
             
'width=' 1771,
             
'marker=' urlencode($marker_args),
             );
    
    
    
$map_url '127.0.0.1:9999/?' implode("&"$mm_args);
    
    
$ch curl_init();
    
curl_setopt($chCURLOPT_URL$map_url);
    
curl_setopt($chCURLOPT_HEADER1);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);

    
$res curl_exec($ch);
    
$status curl_getinfo($chCURLINFO_HTTP_CODE);
    
$err curl_error($ch);
    
curl_close ($ch);
     
    if (
$err){
        print 
"failed to retrieve '{$map_url}' : {$err}";
        exit;
    }
    
    if (
$status != 200){

        list(
$head$data) = explode("\r\n\r\n"$res2);
        
$details = array();

        foreach (
explode("\r\n"$head) as $ln){

            list(
$k$v) = explode(":"$ln2);
            
$k trim($k);
            
$v trim($v);

            if (
preg_match("/^x-error/i"$k)){
                
$k str_replace("x-"""strtolower($k));
                
$details[$k] = strtolower($v);
            }
        }

        echo 
"({$details['errorcode']}) {$details['errormessage']}";
        exit;
    }

    list(
$head$data) = explode("\r\n\r\n"$res2);
    
$map imagecreatefromstring($data);

    
$meta = array();

    foreach (
explode("\r\n"$head) as $ln){

        if (! 
strpos($ln":")){
            continue;
        }

        list(
$k$v) = explode(":"$ln2);
        
$k trim($k);
        
$v trim($v);

        if (
preg_match("/^x-wscompose-/i"$k)){

            
$parts explode("-"$k);
            
            
$major strtolower($parts[2]);
            
$minor strtolower($parts[3]);
            
            if (! isset(
$meta[$major])){
                
$meta[$major] = array();
            }
            
            
$meta[$major][$minor] = $v;
        }
    }
    
    
$coords explode(","$meta['marker']['example']);
    
    
$x_off $coords[2];
    
$y_off $coords[3];

    
imagecopy($map$im$x_off$y_off00$im_width$im_height);
    
imagepng($map);
    exit;
?>