I have a kml file that loads fine in google maps. On the same page I have a text box where the user can enter their location which will add a marker, this works as well.
Where I'm having trouble is if the user enters a location outside the bounds of the kml file, the map won't zoom to include both the kml and the new marker.
If I have preserveViewport=false, it will zoom to fit the kml. If it's true, it will zoom to fit the new marker.
$(document).ready(function () {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var ctaLayer = new google.maps.KmlLayer('KMLLOCATION', { preserveViewport: false });
ctaLayer.setMap(map);
var marker = new google.maps.Marker({ position: new google.maps.LatLng(LAT, LONG), map: map, title: 'You are here', clickable: false, icon: '/media/youarehere.png' });
var bounds = new google.maps.LatLngBounds();
var ll = new google.maps.LatLng(LAT, LONG);
bounds.extend(ll);
map.fitBounds(bounds);
});
EDIT
Thanks to geocodezip for pointing me in the right direction. This is my updated code that works.
$(document).ready(function () {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var layer = new google.maps.KmlLayer('KMLLOCATION', { map: map, preserveViewport: true });
var marker = new google.maps.Marker({ position: new google.maps.LatLng(LAT, LONG), map: map, title: 'You are here', clickable: false, icon: '/media/youarehere.png' });
google.maps.event.addListener(layer, 'defaultviewport_changed', function() {
var bounds = layer.getDefaultViewport();
var ll = new google.maps.LatLng(LAT, LONG);
bounds.extend(ll);
map.fitBounds(bounds);
});
});