Google Maps v3 Zooming specific location - javascript

i'm still learning the javascript not much pro, and this is my 1st post.
JavaScript
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
});
// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
var markers = [{
lat: 35.15074,
lng: -89.955992,
name: "Bob 1"
}, {
lat: 35.149425,
lng: -89.946595,
name: "Bob 2"
}, {
lat: 35.146687,
lng: -89.929837,
name: "Bob 3"
}, {
lat: 35.132264,
lng: -89.937197,
name: "Bob 4"
}];
// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
google.maps.event.addListener(marker, "click", function () {
openInfoWindow(marker);
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
var panorama = null;
var pin = new google.maps.MVCObject();
google.maps.event.addListenerOnce(infowindow, "domready", function () {
panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true
});
panorama.bindTo("position", pin);
});
// Set the infowindow content and display it on marker click.
// Use a 'pin' MVCObject as the order of the domready and marker click events is not garanteed.
function openInfoWindow(marker) {
title.innerHTML = marker.getTitle();
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
}
I had the 4 different places, then i need the 4 webpages to add, how to i tell the browser that i want zooming the specific location. let's say i wanted to zooming at "Bob 1".
Then i rename the webpage as bob1.html. Whenever i click the bob1.html the webpage will zooming zoom: 15 and the marker is center on the map

You don't need to have four different pages unless this is part of the spec?
To set the position and zoom level of the map simply call:
map.setCenter(yourLatLngOrMarkerPosition);
And to set the zoom level:
map.setZoom(yourZoomLevel);
These could be set at any point after the instantiation of the map so perhaps on button clicks or after a period of time?
Hope this helps.
Edit To take into account your requirements (mentioned in the comments) I would submit the relevant url post parameters upon clicking the link. Within the initialize function of each map page you will then need to read these out using something similar to Here (though this uses jQuery) and set the map options as appropriate.
Edit You can read the url post parameters out with php and then echo them in the appropriate places within the google maps calls.
For Example:
map.setZoom(<?php echo $_GET['urlZoomParam'];?>);
Etc.
Some general PHP/MYSQL/Google Maps stack docs: https://developers.google.com/maps/articles/phpsqlajax_v3 https://developers.google.com/maps/articles/phpsqlsearch_v3 http://theoryapp.com/online-store-locator-using-php-mysql-and-google-maps/

Related

Google Maps centre changing issue

I'm using a combination of Google Maps, GeoXML and MarkerClusterer to map historic texts to places. The user can choose the texts they want to map, and the page goes and gets the KML for those group of texts and displays it with MarkerClusterer.
Something is causing the page to recenter over India/China when new texts are selected (bottom left corner: http://lakes.jhadley.net/lit_file.htm.
Here is the primary function that deals with the map:
function loadMap(myLat, myLong, zoomLevel, generatedUrl) {
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: zoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mcOptions = {gridSize: 80, maxZoom: 15};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
markerclusterer = new MarkerClusterer(map, [], mcOptions);
var myParser = new geoXML3.parser({
map: map,
singleInfoWindow:true,
suppressInfoWindows:true,
createMarker:function(placemark){
var point = placemark.latlng;
var info = "<pre" + placemark.name + "<br /><br />" + placemark.description + "</pre>";
var marker = new google.maps.Marker({position:point});
//Suppress the speachbubbles and have them appear in a text window instead
google.maps.event.addListener(marker, 'click', function() {
var text = placemark.description.replace(/ target="_blank"/ig, "");
showInContentWindow(text);
}); //Add listener
markerclusterer.addMarker(marker);
}
});
myParser.parse("http://lakes.jhadley.net/generateKml/"+generatedUrl);
function showInContentWindow(text) {
var sidediv = document.getElementById('kwic_window');
sidediv.innerHTML = text;
} //showInContentWindow
} //function loadMap
I can't personally see why the map centre is being repositioned over India/China when new texts are loaded. Can anyone tell me what I'm missing?
by default geoxml3 attempts to zoom to fit the data. If you don't want it to do that, set the "zoom" option to false. From the documentation:
zoom | boolean (true) | If true, the parser will automatically move the map to a best-fit of the geodata after parsing of a KML document completes.
That is where the "center" of the markers are:
http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/geoxml3_test/SO_20140312_1,4.kml
http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/geoxml3_test/SO_20140312_1.kml

Plotting bus route with Google Maps

I'm working on a property rental site. On the site I'd like to have a Google map, with all of the properties marked, and the local bus routes drawn, so that renters can see the proximity of the properties to the route.
I've achieved the first part of the problem; I've plotted the properties using markers. Now I need to add the bus route.
I've looked in to this and I can't quite work out the best way to achieve it. I looked at polylines and at using this tool, but the route is complex and would take hundreds of co-ordinates.
There is some kind of route api, as in this post but apparently it can only take 8 waypoints. Is that right?
Ideally I'd like to draw the map by selecting a start point, an end point, and dragging the route into place; and then somehow importing that route into what I have.
Here is the exact route that I want to import: http://www2.warwick.ac.uk/services/accommodation/landlords/12busroutes/.
My code to plot the properties is:
var siteRoot = "<?php bloginfo('stylesheet_directory');?>/";
var markers = [
<?php
$my_query = new WP_Query( 'post_type=properties' );
while ($my_query->have_posts()) : $my_query->the_post();
kdev_maps('list');
endwhile; // end of the loop.
?>
];
function googlemap() {
jQuery('#map_canvas').css({'height': '400px'});
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("div");
var title = document.createElement("div");
var boxText = document.createElement("div");
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-117,-200)
,zIndex: null
,boxStyle: {
background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
,opacity: 1
,width: "240px"
,height: "190px"
}
,closeBoxMargin: "10px 0px 2px 2px"
,closeBoxURL: "http://kdev.langley.com/wp-content/themes/langley/images/close.png"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
var infoWindow = new InfoBox(myOptions);
var MarkerImage = siteRoot+'images/house-web-marker.png';
// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title,
content: data.html,
icon: MarkerImage
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.open(map, this);
title.innerHTML = marker.getTitle();
infoWindow.setContent(marker.content);
infoWindow.open(map, marker);
jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
var origcent = new google.maps.LatLng(map.getCenter());
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
closeInfoWindow = function() {
infoWindow.close();
};
google.maps.event.addListener(map, 'click', closeInfoWindow);
google.maps.event.addListener(infoWindow, 'closeclick', function()
{
centermap();
});
function centermap()
{
map.setCenter(map.fitBounds(bounds));
}
}
jQuery(window).resize(function() {
googlemap();
});
Any help is much appreciated.
Its worth looking at two things:
1) The GTFS format (https://developers.google.com/transit/gtfs/reference) this is a csv-based format that allows someone to cross reference transit times and routes, if you are lucky then the data will have been assembled for you for your transit authority :)
2) If you can pull in the coordinates then you can make a line feature as long as you want (within the bounds of browser capacity). This is done in much the same way as you pull in markers, except you pull the features you want into a polyline:
like this (from gmaps docs):
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
you will build your array from php, of course :)
hope that helps.
If you use free google maps you can use a start point, end point and 8 way point. In google maps api premiere you can use 23 way point for routing vehicles

When a marker lies behind open infobox - Event mouseover with InfoBox plugin Google Maps API v3

I'm having trouble with v3 of the Google Maps API and using the InfoBox plugin specifically with respect to this usability issue use case:
Since my map requires a custom infobox to be opened upon hovering the mouse over each respective marker, when the map has 2 markers on it that are close in proximity, even when/if one of the markers lies behind an infobox that is currently open after hovering the other close-by marker, it is triggered when mousing over it marker (even though it's behind the currently open infobox) and the other infobox obstructs the currently/previously opened infobox
I've followed the question and answer process by another poster here: Google Maps API v3 Event mouseover with InfoBox plugin and have followed the recommended code, but i can't wrap my mind around how to prevent markers that lie BEHIND an open infobox to not be triggered until that infobox is closed.
var gpoints = [];
function initializeMap1() {
var Map1MileLatLang = new google.maps.LatLng(39.285900,-76.570000);
var Map1MileOptions = {
mapTypeControlOptions: {
mapTypeIds: [ 'Styled']
},
mapTypeControl: false,
zoom: 14,
center: Map1MileLatLang,
//mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeId: 'Styled'
};
var Map1Mile = new google.maps.Map(document.getElementById("map_canvas"), Map1MileOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });//new
Map1Mile.mapTypes.set('Styled', styledMapType);//new
for ( var i=0; i<5; i++ ) {
gpoints.push( new point(Map1Mile) );
gpoints.push( new point2(Map1Mile) );
}
function popup(_point) {
_point.popup = new InfoBox({
content: _point.content,
pane: 'floatPane',
closeBoxURL: '',
alignBottom: 1
});
_point.popup.open(_point.marker.map, _point.marker);
google.maps.event.addListener(_point.popup, 'domready', function() {
//Have to put this within the domready or else it can't find the div element (it's null until the InfoBox is opened)
$(_point.popup.div_).hover(
function() {
//This is called when the mouse enters the element
},
function() {
//This is called when the mouse leaves the element
_point.popup.close();
}
);
});
}
function point(_map) {
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(39.291003,-76.546234),
map: _map
});
this.content = '<div class="map-popup" style="width:100px;"><div class="map-popup-window"><div class="map-popup-content">Just try to click me!<br/>Hovering over this text will result in a <code>mouseout</code> event firing on the <code>map-popup</code> element and this will disappear.</div></div>';
// Scope
var gpoint = this;
// Events
google.maps.event.addListener(gpoint.marker, 'mouseover', function() {
popup(gpoint);
});
}
function point2(_map) {
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(39.295003,-76.545234),
map: _map
});
this.content = '<div class="map-popup" style="width:100px;"><div class="map-popup-window"><div class="map-popup-content">Just try to click me!<br/>Hovering over this text will result in a <code>mouseout</code> event firing on the <code>map-popup</code> element and this will disappear.</div></div>';
// Scope
var gpoint = this;
// Events
google.maps.event.addListener(gpoint.marker, 'mouseover', function() {
popup(gpoint);
});
}
After doing experimenting, i suspect this issue is irrelevant to z-index... am i correct in understanding this needs to be caught in the javascript?
Any help or advice would be greatly appreciated!
Adding optimized: false attribute for your markers should solve the problem.
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(39.295003,-76.545234),
map: _map,
optimized: false
});

google maps api v3 marker click not working

not sure where the problem lies with this, i created a google map with custom markers a few months back using v3 of the api. the info windows were working back then.
i have been porting it onto a new site and cant get the info window to open, the js alerts in the right point when creating the click event but the click event does not fire all i can do is drag the map, so i looked at the last site i did, and its not working there either now.
so not sure how to fix this, the code i have to create ther info window is as follows:
markersArray.push(marker);
markersPosArray.push(myLatLng);
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(myData, marker) {
alert('creating listener for: '+marker);
// Creating the event listener. It now has access to the values of
// myData and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
//create thecontent for the infowindow
alert('creating info window');
var content = 'hello there'; //createContent(myData);
infowindow.setContent(content);
infowindow.open(map, marker);
});
})(myData, marker);
maybe something has changed in the api that i am unaware off?
the testpage can be seen at: http://www.disposalknowhow.com/locator.php
In the locator use the following to obtain results:
type: electrical/electronics - item: computers - radius: 100 - postcode: n11hl
the previous one i did that is not working either now can be seen at: http://www.focus-on-plants.com/locator_iconed.php
(can use any parameters here in the form)
UPDATE:
in reply to treffys answer:
the infowindow is defined when i create the map:
var myLatLng = new google.maps.LatLng(51.470, -0.00);
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var gotIcons = false;
var iconImageArray = {image:{}, size:{}, sizeX:{}, sizeY:{}, origin:{}, originX:{}, originY:{}, anchorpoint:{}, anchorpointX:{}, anchorpointY:{}};
var iconShadowArray = {image:{}, size:{}, sizeX:{}, sizeY:{}, origin:{}, originX:{}, originY:{}, anchorpoint:{}, anchorpointX:{}, anchorpointY:{}};
var iconShapeArray = {poly:{}, coord:{}};
var myIconArray = {icon:{}, shadow:{}, shape:{}}
var infowindow = new google.maps.InfoWindow();
var markersArray = []; // to store out markers
var markersPosArray = []; // to store lat/lang of markers for zooming function
var markersInfoArray = [];
// MAP OPTIONS
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_RIGHT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
}
};//end map options
var map = new google.maps.Map(document.getElementById("loc_map"), myOptions);
I am using the following code to display an info bubble:
var info_pane = new google.maps.InfoWindow({
content: info,
disableAutoPan: false,
maxWidth: '300px'
});
info_pane.open(map, marker);

Google Maps API v3: Close infowindow when DOM element is clicked

I'm playing around with Google maps for the first time, so I looked at a nice tutorial over at CSS Tricks: http://css-tricks.com/google-maps-slider/ I like working with jQuery better than pure JS, and this tutorial makes a nice way to click on a place in a list to display the marker in the map.
I liked it that way, but I need to add infowindows to the marker. Which I did, but when I click on a place on the list and the map pans away, the infowindow stays open! I think it's because I need to attach the infowindow.close() to the event of clicking on a "#locations li".
Here's my code, which runs on document.ready:
$(function() {
var chicago = new google.maps.LatLng(41.924832, -87.697456),
pointToMoveTo,
first = true,
curMarker = new google.maps.Marker({}),
$el;
var myOptions = {
zoom: 10,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#map_canvas")[0], myOptions);
$("#locations li").click(function() {
$el = $(this);
if (!$el.hasClass("hover")) {
$("#locations li").removeClass("hover");
$el.addClass("hover");
if (!first) {
// Clear current marker
curMarker.setMap();
// Set zoom back to Chicago level
// map.setZoom(10);
}
// Move (pan) map to new location
function move(){
pointToMoveTo = new google.maps.LatLng($el.attr("data-geo-lat"), $el.attr("data-geo-long"));
map.panTo(pointToMoveTo);
}
move();
// Add new marker
curMarker = new google.maps.Marker({
position: pointToMoveTo,
map: map
});
// Infowindow: contenido
var contentString = '<p>'+$el.find("h3").html()+'</p>';
contentString += 'hola' ;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
content: contentString
});
// On click, zoom map
google.maps.event.addListener(curMarker, 'click', function() {
//map.setZoom(14);
infowindow.open(map,curMarker);
});
It looks like you're creating a new InfoWindow for each marker. Quoting from the Google Maps API Docs:
If you only want one info window to display at a time (as is the behavior on Google Maps), you need only create one info window, which you can reassign to different locations or markers upon map events (such as user clicks).
Therefore, you may simply want to create one InfoWindow object just after you initialize your map, and then handle the click event handler as follows:
google.maps.event.addListener(curMarker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, curMarker);
});
Then the InfoWindow should automatically close when you click on a new marker without having to call the close() method.

Categories