I was playing around recently trying to get a proper “map” to show, and then a nice StreetView alongside it. Google have a good example here:
https://google-developers.appspot.com/maps/documentation/javascript/examples/streetview-simple
Here is an example of what we are going to try and achieve
This is all good and well if you have the lat/lng values already. If you want to pass in a custom address to find, then its a bit more complex. I ended up spending quite a while trying to get this right, and pulling out a fair amount of hair
The problem comes in the fact that if you try and run dosearch() *before* the map is created, it actually runs AFTER the code (due to the way it runs asynchronously). To fix this you have to do it a little bit backwards. First of all you need to load jQuery, and the Google Maps API, with:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
Then the following code can be run:
var geocoder, test, map, panorama; // make globally available!
jQuery(document).ready( function($) {
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
var baselatlng = new google.maps.LatLng(42.345573,-71.098326);
var mapOptions = {
center: baselatlng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map( document.getElementById('map_canvas'), mapOptions );
var panoramaOptions = {
position: baselatlng,
pov: {
heading: 34,
pitch: 10,
zoom: 1
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
dosearch("Address, City, State, ZIP, Country");
}
function dosearch(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(new google.maps.LatLng( results[0].geometry.location.lat(), results[0].geometry.location.lng() ) );
map.setZoom(18);
panorama.setPosition(new google.maps.LatLng( results[0].geometry.location.lat(), results[0].geometry.location.lng() ));
} else {
if (status == "ZERO_RESULTS") {
alert("Sorry, we couldn't find any places matching the name you entered.");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}
});
}
Then just place these wherever you want the map to show up:
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="width: 400px; height: 300px;"></div>
Depending on how your site is setup, you would just pass in the address via:
dosearch("Address, City, State, ZIP, Country");
This also means you can update the address from the page itself (i.e offer an input field which they can enter a custom address in, which would find the record on the map)
I hope that helps someone as it drove me around the bend as to why it wouldn’t work for so long!
Categories: Google Maps v3 • jQuery