Google Maps centre changing issue - javascript

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

Related

How do I add a user-input marker to Google Maps widget on my website, and get the latitude and longitude data from it?

How do I add a user-input marker to Google Maps widget on my website, and get the latitude and longitude data from it?
Right now I am building an application which has to allow users to drop a marker to any location so that I can get that data and process it.
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8,-187.3),
mapTypeId: 'terrain'
});
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
// This example uses a local copy of the GeoJSON stored at
// http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
</script>
Right now I am using this, but this doesn't offer any user submitted markers.
Try running this working jsfiddle for demonstration and guidance on how users can place markers on a Google map. Note that it's based off of Google's example on adding and removing markers.
Full JS code below:
var map;
var markers = [];
function initMap() {
var haightAshbury = {
lat: 37.769,
lng: -122.446
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: haightAshbury,
mapTypeId: 'terrain'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
You can get the marker's coordinates from the map's click event listener, e.g.:
map.addListener('click', function(event) {
console.log(event.latLng.lat());
console.log(event.latLng.lng());
addMarker(event.latLng);
});
Or from the addMarker method:
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
markers.push(marker);
}
Hope this helps!

Google maps stop showing points v3

Hi i have trouble to find what case a problem to showing the way point on goggle maps as there were no changes in the code for a wile. way point stop showing about last week. im not familiar with google api
var map = null;
var markerArray = []; //create a global array to store markers
var myPoints =
[ [52.664167, -8.509825,' HQ','favicon.ico'] ,[52.836346, -6.913117,'point 1','http://maps.google.com/mapfiles/ms/icons/red.png ' ],[52.836202, -6.912101,'point2','http://maps.google.com/mapfiles/ms/icons/red.png ' ]];
function initialize() {
var myOptions = {
zoom:7,
center: new google.maps.LatLng(53.112, -7.448),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var mcOptions = {
gridSize: 30,
maxZoom: 15
};
var mc = new MarkerClusterer(map, [], mcOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Add markers to the map
// Set up markers based on the number of elements within the myPoints array
for(var i=0; i<myPoints.length; i++){
createMarker(new google.maps.LatLng(myPoints[i][0], myPoints[i][1]), myPoints[i][2], myPoints[i][3]);
}
mc.addMarkers(markerArray , true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, html, icons) {
var contentString = html;
var links = icons;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: links ,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
// marker.setAnimation(google.maps.Animation.BOUNCE);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker); //push local var marker into global array
}
window.onload = initialize;
<script src="https://maps.googleapis.com/maps/api/js?v=3"
type="text/javascript"></script>
<div id="map" style="width: 800px; height: 750px;" ></div>
Any suggestions?
It seems that you are using MarkerClusterer which is a part of google maps utility library, which was moved recently. Somebody probably referenced the library straight from code.google.com/svn/... in your project, where it's not available anymore and that's why it's broken. You need to find all libraries which are referenced from https://google-maps-utility-library-v3.googlecode.com/svn and replace then with your own links.
Check this SO question, user had very similar issues to yours.
Also! check this question and answers on SO!!, there are users who experienced issues with the same library, to get more information. Read all answers, as replacing https://google-maps-utility-library-v3.googlecode.com/svn with https://rawgit.com/googlemaps/... is not a correct solution, you should download the library assets into your project and reference them from there or use CDN (but not git!).

Google Maps v3 Zooming specific location

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/

how to open popup on click of a marker from the directions service?

UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

Both custom and original markers are showing google maps api v3

For some reason I have both markers showing.. http://picpaste.com/Screen_Shot_2013-10-02_at_10.55.41_AM-qKfxgyCO.png
There's also a box surrounding the whole thing. Any ideas why these would be showing up?
var gmap;
function initialize() {
var myLat = new google.maps.LatLng(33.991447,-84.09403);
var mapOptions = {
zoom: 13,
center: myLat,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmap = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var mapIcon = '../fw/img/map-marker-lowres.png';
var infowindowContent ='<div class="mapbox"><p><strong>The Arena at Gwinnett Center</strong></p>' + '<p>6400 Sugarloaf Pkwy<br>Duluth, GA 30097<br>(770) 813-7500</p>' + '> get driving directions</div>';
var infowindow = new google.maps.InfoWindow({
content: infowindowContent,
maxWidth: 250,
});
var marker = new google.maps.Marker({
position: myLat,
icon: mapIcon,
map: gmap
});
marker.setMap(gmap);
infowindow.open(gmap,marker);
}
The general answer (now that you have asked the right question) is that the standard InfoWindow can't be styled the way you want. You need to use a third party library like InfoBubble or InfoBox or create your own custom InfoWindow replacement.

Categories