Change map center in googlemap api - javascript

I want to change map center. my code is below.
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var point2=[];
// mark infowindow
downloadUrl("markinfoan.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("time");
var ss = markers[i].getAttribute("secspray");
var pd = markers[i].getAttribute("secdis");
var ms = markers[i].getAttribute("meanspray");
var td = markers[i].getAttribute("totaldis");
var tss = markers[i].getAttribute("totalsecspray");
var tst = markers[i].getAttribute("totalsectime");
var mpoint = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var html = "<b>" + "Time:"+ "</b>"+name +"<br/>" + "<b>" +"Spray:"+"</b>"+ss+"<br/>"+ "<b>" +"MeanSpray:"+"</b>"+ms+"<br/>"+ "<b>" +"TotalsectionSpray:"+"</b>"+tss+"<br/>"+ "<b>" +"Dis:"+"</b>"+pd+"<br/>"+ "<b>" +"Total dis:"+"</b>"+td+"<br/>"+ "<b>" +"Totaltime:"+"</b>"+tst+"<br/>";
var icon = customIcons[pd] || {};
var marker = new google.maps.Marker({
map: map,
position: mpoint,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
//total route
downloadUrl("rec_an.xml", function(data) {
var point1 = [];
var xml1 = data.responseXML;
var markers1 = xml1.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers1.length; i++) {
point1[i] = new google.maps.LatLng(
parseFloat(markers1[i].getAttribute("latitude")),
parseFloat(markers1[i].getAttribute("longitude")));
}
var flightPath = new google.maps.Polyline({
path: point1,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 2.0,
strokeWeight: 4
});
flightPath.setMap(map);
});
// mark infowindow route
downloadUrl("markinfoan.xml", function(data) {
// var point2 = [];
var xml2 = data.responseXML;
var markers2 = xml2.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers2.length; i++) {
point2[i] = new google.maps.LatLng(
parseFloat(markers2[i].getAttribute("latitude")),
parseFloat(markers2[i].getAttribute("longitude")));
}
var flightPath = new google.maps.Polyline({
path: point2,
geodesic: true,
strokeColor: '#0066FF',
strokeOpacity: 2.0,
strokeWeight: 4
});
flightPath.setMap(map);
});
alert(point2);
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(point2[0]),
zoom: 12,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
if (request.status === 200) {
alert("Total route, Infowindow");
alert(point2[0]);
} else {
alert('There was a problem with the request.');
}
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 1000px; height: 800px"></div>
I want to change map center from (37.5,126.9) to point2[0].
point2[0] is a location recorded in xml file.
When I run my code, "alert(point2)" represent nothing. How can I fix it?
Thank you.

downloadUrl is an asynchronous request, you need to use the value of point2 in its callback function when it has a value.
downloadUrl("markinfoan.xml", function(data) {
var xml2 = data.responseXML;
var markers2 = xml2.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers2.length; i++) {
point2[i] = new google.maps.LatLng(
parseFloat(markers2[i].getAttribute("latitude")),
parseFloat(markers2[i].getAttribute("longitude")));
}
var flightPath = new google.maps.Polyline({
path: point2,
geodesic: true,
strokeColor: '#0066FF',
strokeOpacity: 2.0,
strokeWeight: 4
});
flightPath.setMap(map);
// set the map center inside the callback function, where point2 exists
map.setCenter(point2[point2.length-1]); // <-- add this sets the center of the map to the last point on the path
});

Related

How To get all latitude and longitude from source to destination place on selection of suggested routes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i want to fetch all the latitude and longitude between origin place to destination place.
For that i have written following script but it will not give me the latitude and longitude between those two place.
<script type="text/javascript">
var directionDisplay;
var directionsRenderer;
var directionsService = new google.maps.DirectionsService();
var map;
function drawMap(midpoint) {
var mid = midpoint.split(",");
var start = new google.maps.LatLng(mid[0], mid[1]);
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start,
mapTypeControl: false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var input = (document.getElementById('origin'));
var inputdestination = (document.getElementById('destination'));
var types = document.getElementById('changetype-all');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var autocompletedestination = new google.maps.places.Autocomplete(inputdestination);
autocompletedestination.bindTo('bounds', map);
}
function getRendererOptions(main_route) {
if (main_route) {
var _colour = '#00458E';
var _strokeWeight = 4;
var _strokeOpacity = 1.0;
var _suppressMarkers = false;
}
else {
var _colour = '#ED1C24';
var _strokeWeight = 2;
var _strokeOpacity = 0.7;
var _suppressMarkers = false;
}
var polylineOptions = { strokeColor: _colour, strokeWeight: _strokeWeight, strokeOpacity: _strokeOpacity };
var rendererOptions = { draggable: true, suppressMarkers: _suppressMarkers, polylineOptions: polylineOptions };
return rendererOptions;
}
function renderDirections(result, rendererOptions, routeToDisplay) {
if (routeToDisplay == 0) {
var _colour = '#00458E';
var _strokeWeight = 4;
var _strokeOpacity = 1.0;
var _suppressMarkers = false;
}
else {
var _colour = '#ED1C24';
var _strokeWeight = 4;
var _strokeOpacity = 0.7;
var _suppressMarkers = false;
}
// if (routeToDisplay == 0) _colour = "#FF0000";
// create new renderer object
var directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
suppressMarkers: _suppressMarkers,
polylineOptions: {
strokeColor: _colour,
strokeWeight: _strokeWeight,
strokeOpacity: _strokeOpacity
}
});
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById('directions_panel'));
directionsRenderer.setDirections(result);
directionsRenderer.setRouteIndex(routeToDisplay);
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
Below if condition is used for get all latitude and longitude between two places but it is not wokrs.
if (response.routes && response.routes.length > 0) {
var routes = response.routes;
for (var j = 0; j < routes.length; j++) {
var points = routes[j].overview_path;
var ul = document.getElementById("vertex");
for (var i = 0; i < points.length; i++) {
var li = document.createElement('li');
li.innerHTML = getLiText(points[i]);
ul.appendChild(li);
}
}
}
}
});
}
function getLiText(point) {
var lat = point.lat(),
lng = point.lng();
return "lat: " + lat + " lng: " + lng;
}
function requestDirections(start, end, routeToDisplay, main_route) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: main_route
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
if (main_route) {
var rendererOptions = getRendererOptions(true);
for (var i = 0; i < result.routes.length; i++) {
renderDirections(result, rendererOptions, i);
}
}
else {
var rendererOptions = getRendererOptions(false);
renderDirections(result, rendererOptions, routeToDisplay);
}
}
});
}
</script>
Below is the body:
<body>
<div id="vertex-container">
<label>Points</label>
<ul id="vertex">
</ul>
</div>
<div>
//...all the other input and button
//....
</body>
From above script i can get all the route from origin place to destination place but i didnt get the all latitude and longitude between those place.
you can see that i can get suggested route between two place.
But now i want to print all latitude and longitude between those route which i am selecting.
Suppose here 3 routes are there .
now suppose i am selecting 1st then it will fetch all the latitude and longitude between those places only for that route
Now suppose i am slecting 2nd suggested route then it will display all latitude and longitude between that route
so now ,
how can i get all the latitude and longitude between those places for selected route from suggested routes?
You have to loop through the alternate routes and for each route loop through all steps.
Here is an example that shows how to draw all the alternate routes to the map and place a marker at each step. I have used different colors so you can clearly identify each route.
Note that it uses the start_location of each step. We don't know if that is what you need.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var center = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
directionsDisplay.setMap(map);
var start = "Yamuna Nagar, Haryana, India";
var end = "New Delhi, India";
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method],
provideRouteAlternatives: true
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var routesSteps = [];
var routes = response.routes;
var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'black'];
for (var i = 0; i < routes.length; i++) {
new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i,
polylineOptions: {
strokeColor: colors[i],
strokeWeight: 4,
strokeOpacity: .3
}
});
var steps = routes[i].legs[0].steps;
var stepsCoords = [];
for (var j = 0; j < steps.length; j++) {
stepsCoords[j] = new google.maps.LatLng(steps[j].start_location.lat(), steps[j].start_location.lng());
new google.maps.Marker({
position: stepsCoords[j],
map: map,
icon: {
path: 'M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0',
scale: .5,
fillColor: colors[i],
fillOpacity: .3,
strokeWeight: 0
},
title: steps[j].maneuver
});
}
routesSteps[i] = stepsCoords;
}
// Here is your array of routes steps coordinates
console.log('routesSteps', routesSteps);
}
});
}
initialize();
JSFiddle demo

Markers not showing in Google Maps API

I have just loaded the following code into my webpage and after many hours of troubleshooting, I can't get the Markers to show up?
I have confirmed that the parsing php file is working.
Javascript:
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var customIcons = {
accom: {
icon: 'images/google_map_icon_green.png'
},
food: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(
<?php if ($_COOKIE[company] == 'ch') { echo $ch[hls_lat].", ".$ch[hls_long]; } elseif ($_COOKIE[company] == 'shc') { echo $shc[hls_lat].", ".$shc[hls_long]; } elseif ($_COOKIE[company] == 'lmh') { echo $lmh[hls_lat].", ".$lmh[hls_long]; }?>),
zoom: 12,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow = new google.maps.InfoWindow;
downloadUrl("required/xml_parse.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
SetMap: map_canvas,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map_canvas, infoWindow, html);
}
});
function bindInfoWindow(marker, map_canvas, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
HTML:
<br />
<div class="inner-article-header"><h2>Map of Locations</h2></div>
<div id="map_canvas" style="height:565px; width:754px; margin:2px;"></div>
</div>
This is incorrect:
SetMap: map_canvas,
Should be (see MarkerOptions in the documentation):
map: map,
corrected marker constructor:
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
Add the parsing of the XML into the initialize function, so map is valid when you add the markers:
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(0,0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
downloadUrl("example.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
working example (using one of my existing xml files, since you didn't provide any example data)
You have additional problems with the call to bindInfoWindow and its definition (map_canvas, should be map)

Grouping polygons

i have some project using polygon, i want to make some polygon with different fill color, but also i want to make it all in one group, i mean when i drag any polygon, the other one within same group get drag together, how i make that possible?
This is my code:
var marker;
var map;
var elevator;
var listenerHandle;
function initialize()
{
var mapOpt = {
center:new google.maps.LatLng(-8.664523972355582,115.2165412902832),
maxZoom:30,
zoom:14,
panControl:false,
zoomControl:false,
mapTypeControl:true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
position: google.maps.ControlPosition.BOTTOM_LEFT
},
scaleControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:false,
mapTypeId:google.maps.MapTypeId.HYBRID
};
map=new google.maps.Map(document.getElementById("map_pan"),mapOpt);
elevator = new google.maps.ElevationService();
var infoWindow = new google.maps.InfoWindow;
downloadUrl("addons/view/xml.php", function(data) {
var xml = data.responseXML;
var paths = xml.documentElement.getElementsByTagName("path");
for (var i = 0; i < paths.length; i++) {
var sitename = paths[i].getAttribute("sitename");
var koordinat = paths[i].getAttribute("koordinat");
var koor = koordinat.split(";");
var koorbts = paths[i].getAttribute("koorbts");
var warna = paths[i].getAttribute("color");
var latlng = [];
var polygon ="";
var html = sitename;
for (var j = 0; j<koor.length; j++){
var kordi = koor[j].split(",");
var lat = kordi[0];
var lng = kordi[1];
latlng[j] = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
}
polygon = new google.maps.Polygon({
map: map,
paths: latlng,
strokeColor: warna,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: warna,
fillOpacity: 0.8,
draggable: true,
geodesic: true
});
bindInfoWindow(polygon, koorbts, map, infoWindow, html);
}
});
}
function bindInfoWindow(polygon, koorbts, map, infoWindow, html) {
google.maps.event.addListener(polygon, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map);
var kor = koorbts.split(",");
var lat = kor[0];
var lng = kor[1];
latlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
infoWindow.setPosition(latlng);
document.getElementById('x_lat').value = lat;
document.getElementById('y_lng').value = lng;
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function mapclick(){
google.maps.event.removeListener(listenerHandle);
listenerHandle = google.maps.event.addListener(map,'click',function(event){
if (!marker) {
marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable:true
});
}
else { marker.setPosition(event.latLng); }
updateMarkerPosition(marker.getPosition());
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());});
});
}
function updateMarkerPosition(latLng) {
var floatlat = parseFloat(latLng.lat());
var floatLng = parseFloat(latLng.lng());
var latx = floatlat.toFixed(6);
var lngy = floatLng.toFixed(6);
$("#x_lat").val(latx);
$("#y_lng").val(lngy);
}
function deleteOverlays() {
google.maps.event.removeListener(listenerHandle);
marker.setMap(null);
marker="";
}
google.maps.event.addDomListener(window, 'load', initialize);
So what you're needing to do is to create a complex polygon. A "simple" polygon is basically your normal multi-sided closed shape. A "complex" polygon is interpreted by Google Maps as a 'single' shape, denoted as an array of simple polygons.
I am working on something similar where I allow the user to draw out multiple areas, but belong together as a simple entity. I know this is late, but to accomplish this, when you're creating your polygons, for each one, you can make use of the Polygon.setPaths() function which you should set up each Array as a simple closed polygon, so that the Polygon shape is comprised of multiple sets of simple paths.
Then, you can store and set that Polygon so that when you drag/color one of those simple polygons, all the rest in the same shape will be affected too.
Apologies for the late and abstract answer.

Markers not shown on Multiple Polylines

function disp_initialize()
{
var bike=<?php echo $_GET['bike_id']; ?>;
$.ajax({
"dataType": "json",
"type": "POST",
"url": "home.php?bike_id="+bike,
success: function(data) {
if(data.sMsg==0)
{
$("#map-canvas").hide();
}
else if(data.sBlankMsg==0){
$("#map-canvas").hide();
}
else
{
initialize(data);
}
}
});
}
function initialize(flightPlanCoordinates_arr)
{
var flightPlanCoordinates_arr = flightPlanCoordinates_arr.mapData;
var flightPlanCoordinates_arr_p = new Array();
var j = 0;var k = 0;
var store = new Array();
for(var i in flightPlanCoordinates_arr)
{
if(j==0)
{
flightPlanCoordinates_arr_p[j] = flightPlanCoordinates_arr[i];
j++;
}
else if(flightPlanCoordinates_arr_p[j-1]['state']==1 && flightPlanCoordinates_arr[i]['state']==0)
{
flightPlanCoordinates_arr_p[j] = flightPlanCoordinates_arr[i];
j++;
}
else if(flightPlanCoordinates_arr_p[j-1]['state']==0 && flightPlanCoordinates_arr[i]['state']==1)
{
store[k]=j;
flightPlanCoordinates_arr_p[j] = flightPlanCoordinates_arr[i];
j++;k++;
}
}
//console.log(store);
var flightPlanCoordinates = new Array();
for(var i in flightPlanCoordinates_arr_p)
{
flightPlanCoordinates[i] = new google.maps.LatLng(flightPlanCoordinates_arr_p[i]["latitude"],flightPlanCoordinates_arr_p[i]["longitude"]);
}
if(flightPlanCoordinates_arr != '')
{
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(flightPlanCoordinates_arr[0]["latitude"],flightPlanCoordinates_arr[0]["longitude"]),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
}
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var Colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#000000", "#FFFF00", "#00FFFF", "#FF00FF"];
for (var i = 0; i < flightPlanCoordinates.length; i++)
{
if(jQuery.inArray(i+1,store)===-1)
{
var colour = Colors[i];
var flightPath = new google.maps.Polyline({
path: [flightPlanCoordinates[i], flightPlanCoordinates[i+1]],
geodesic: true,
strokeColor: '#FFFF00',
strokeOpacity: 2.0,
strokeWeight: 10,
map: map
});
}
}
flightPath.setMap(map);
var location = "";
var location_details = "";
var speed="";
for(var i in flightPlanCoordinates_arr)
{
location = flightPlanCoordinates_arr[i]["location"];
location_details = flightPlanCoordinates_arr[i]["location_details"];
speed = flightPlanCoordinates_arr[i]["speed"];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(flightPlanCoordinates_arr[i]["latitude"],flightPlanCoordinates_arr[i]["longitude"]),
map: map
});
marker.setIcon('images/bike.png');
}
new google.maps.event.addListener(flightPath, 'mouseover', function(event) {
var populationOptions = {
strokeColor: '#11C111',
strokeOpacity: 0.8,
strokeWeight: 4,
fillColor: 'transparent',
fillOpacity: 4,
map: map,
center: event.latLng,
position: event.latLng,
radius: 40
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
attachSecretMessage(marker, contentHtml,map);
});
new google.maps.event.addListener(flightPath, 'mouseout', function(event) {
var marker = new google.maps.Marker({
position: event.latLng,
});
// Add the circle for this city to the map.
cityCircle.setMap(null);
});
}
function attachSecretMessage(marker, contentHtml, map) {
var infowindow = new google.maps.InfoWindow({
position: marker.position,
content: contentHtml
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
}
mapData is a JSON response which brings 'Latitude','Longitude','Speed','State','Location' values.
I have drawn polylines for the Lats and Longs , but the markers are not displayed.And getting this error
TypeError: f is undefined
Your design is not clear to me exactly.
If you want to get marker visible in mouseout event listener than you have to provide map value. For example:
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
In that case you have to make map global. Currently it is locally defined in function initialize(). So:
var map;
function initialize(flightPlanCoordinates_arr) {
...
map = new google.maps.Map(document.getElementById('map'), mapOptions);
...
}
Additionally, it seems that this for loop
for (var i = 0; i < flightPlanCoordinates.length; i++) {
should be initialized as:
for (var i = 0; i < flightPlanCoordinates.length - 1; i++) {
Update: see example at jsbin. It's best I can get because I do not understand whole logic of some variables checking. If you set prober icon marker will be set. Note: I cannot perform that ajax call so I had to model data.

Google Maps API V3 Clearing Markers Before Update

I have searched and searched for an answer with no luck. I can get the xml data to display fine and it appears that my markers refresh but just wont remove the previous one so they stack up. Any help would be great! I just need to remove the markers before the new ones appear. Thanks!
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var markersArray = [];
var customIcons = {
restaurant: {
icon: 'pin.png',
shadow: ''
},
bar: {
icon: 'loc1.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
airport: {
icon: 'loc2.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.0923204, -95.9042496),
zoom: 5,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
setInterval(function() {
downloadUrl("phpsqlajax_genxmlall.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
resetMarkers(markersArray)
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var amount = markers[i].getAttribute("amount");
var time = markers[i].getAttribute("time");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<br/>$" + amount + " at " + time;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}, 5000);
}
function resetMarkers(arr){
for (var i=0;i<arr.length; i++){
arr[i].setMap(null);
}
//reset the main marker array for the next call
arr=[];
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 1400px; height: 800px"></div>
</body>
The problem is, you are not adding your markers to markerArray, it stays empty, so there is nothing to remove when you call resetMarkers
After creating the marker, add it to markerArray:
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
markerArray.push(marker);

Categories

Resources