Как сохранить результаты геокодирования в базе данных - PullRequest
0 голосов
/ 04 ноября 2011

В настоящее время я строю несколько маркеров на карте Google (V3) через данные Wordpress с кодом ниже. Я использую адрес (геокод) и хочу, чтобы никому не приходилось вводить координаты широты и долготы в Wordpress.

В настоящее время у меня есть задержка между каждым запросом, чтобы избежать ограничения геокодирования, это не идеально, и мне нужно, чтобы маркеры отображались мгновенно.

Читая тему о том, как избежать предела геокодирования, люди предлагают сохранить результаты геокодирования в базе данных, а затем оттуда читать результаты геокодирования в базе данных вместо того, чтобы фактически снова геокодировать маркер (и использовать другой запрос геокодирования). ).

Как бы я это сделал? Как я могу сохранить результаты геокодирования по маркеру в базе данных, а затем прочитать результаты по широте / долготе оттуда в?

p.s Я пробовал Google Fusion Tables, но он не работает с динамическими данными.

Вот мой текущий код:

<script type="text/javascript"> 
(function() { 

window.onload = function() { 
 var mc;
// Creating an object literal containing the properties we want to pass to the map 
var options = { 
zoom: 0, maxZoom: 0, 
center: new google.maps.LatLng(52.40, -3.61), 
mapTypeId: google.maps.MapTypeId.ROADMAP 
}; 

// Creating the map 
var map = new google.maps.Map(document.getElementById('map'), options); 

// Creating a LatLngBounds object 
var bounds = new google.maps.LatLngBounds(); 

// Creating an array that will contain the addresses 
var places = []; 

// Creating a variable that will hold the InfoWindow object <img src="'.$fields->company_logo.'" /> 
var infowindow; 
mc = new MarkerClusterer(map);
<?php
$pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
$popup_content = array();
foreach($pages as $post)
    {
    setup_postdata($post);
    $fields = get_fields(); 
    $popup_content[] = '<p>'.$fields->company_name.'</p><br /><a href="'.get_page_link($post->ID).'">View profile</a>';
    $comma = ", ";
    $full_address = "{$fields->address_line_1}{$comma}{$fields->address_line_2}{$comma}{$fields->address_line_3}{$comma}{$fields->post_code}";
    $address[] = $full_address;
    }
wp_reset_query();
echo 'var popup_content = ' . json_encode($popup_content) . ';';
echo 'var address = ' . json_encode($address) . ';';
?>

var geocoder = new google.maps.Geocoder(); 

var markers = [];

// Adding a LatLng object for each city 
function geocodeAddress(i) {
     geocoder.geocode( {'address': address[i]}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            places[i] = results[0].geometry.location;

            // Adding the markers 
            var marker = new google.maps.Marker({position: places[i], map: map});
            markers.push(marker);
            mc.addMarker(marker);

            // Creating the event listener. It now has access to the values of i and marker as they were during its creation
            google.maps.event.addListener(marker, 'click', function() {
                // Check to see if we already have an InfoWindow
                if (!infowindow) {
                    infowindow = new google.maps.InfoWindow();
                }

                // Setting the content of the InfoWindow
                infowindow.setContent(popup_content[i]);

                // Tying the InfoWindow to the marker 
                infowindow.open(map, marker);
            });

            // Extending the bounds object with each LatLng 
            bounds.extend(places[i]); 

            // Adjusting the map to new bounding box         alert("Geocode was not successful for the following reason: " + status + popup_content[i]);  
            map.fitBounds(bounds) 
        } else { 

        }
    })
}

function geocode() {
    if (geoIndex < address.length) {
        geocodeAddress(geoIndex);
        ++geoIndex;
    }
    else {
        clearInterval(geoTimer);
    }
}
var geoIndex = 0;
var geoTimer = setInterval(geocode, 1000);  // Delay

var markerCluster = new MarkerClusterer(map, markers); 
} 
})
(); 
</script> 

Обновление: После дальнейших исследований я обнаружил, что это - Как мне использовать Google Maps geocoder.getLatLng () и сохранять его результат в базе данных? , и этот Невозможно десериализовать объект GoogleMaps DirectionsResult . Они кажутся мне общей вещью, но я не знаю, как включить это в мой пример.

...