Google MAP API with PHP and Javascript - javascript

I am very new in HTML5 area, I am trying to make a program that will fetch the data from mysql with PHP and use geocode to transform from address to Latlng. it is a LBS program, and I was trying for 2 weeks, my question is I cannot put markers into the Google MAP, I did the locator corrected and map is loaded, but the marker cannot land on map, please help!! thank you, and I am really appreciate your help. if this code has any mistake or problem please give me generous advice, I am very new in this area, and I am trying to learn more in HTML5 Javascript, thank you and I am very appreciate your advice!!!
my code is here:
'enter code here`<?php
require_once 'Common/system_start.php';
$sql="select addr from tab_mem order by sn desc ";
$result= mysql_query($sql);
$data=mysql_fetch_assoc($result);
$row=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
echo '<script type="text/javascript">';
echo var n = new Array("', join($n,'","'), '");';
echo '</script>';
?>
<code>
<pre>
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no"/>
<!-- Google Maps -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js? `enter code here`sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js">
</script>
<!-- program main -->
<script type="text/javascript">
var iterator=0;
markers=n;
var a=n.length;
function load() {
var map_div = document.getElementById("map_div");
//initial locator
navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 `enter code here`});
// decide location
function onSuccess(position){
//fetching latlng from GPS
var latlng = new google.maps.LatLng(position.coords.latitude,
`position.coords.longitude);
// display map
var gmap = new google.maps.Map(
map_div, {
zoom:16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//drop the marker
function drop() {
for (var i = 0; i < a; i++) {
setTimeout(function() {
}, i * 200);
}
}
//decode address to latlng
//pass address data from PHP
for(var i in n){
var address=n;
geocoder=new google.maps.Geocoder();
geocoder.geocode({'address':address},function(results,status){
if(status==google.maps.GeocoderStatus.OK){
//alert("AAA");
address=results(i).geometry.location;
function addMarker() { markers.push(new google.maps.Marker({
postion:results(i).geometry.location,
map:gmap,
animation:google.map.animation.DROP
//iterater++;
}));
//itertor++;
}
//markerNearBy.setMap(map);
}else{
alert("Geocode was not sucessful for the following reason:"+status);
}
});
}
}
}
function onError(error) {
alert('code: '+ error.code+ '\n'
+'message: ' + error.message + '\n');
}
</script>
</head>
<body onLoad="load()">
<!-- Map Display place -->
<div id="map_div" style="width:320px; height:480px;"></div>
</body>
</html>
<code>

Your code doesn't look well-formed. You have the "addMarker" function defined inside your "for" loop. Also, it's not getting called anywhere.
Take a look at the sample code Google provides for working with markers and overlays and try to emulate it. The sample only uses one marker, but you can simply iterate through your results. You've got the right intentions by adding your Marker objects to an array, and setting your map object to the map property of the Marker, but you will need to format/restructure your code first or it will not work.
Sample code:
https://developers.google.com/maps/documentation/javascript/overlays#RemovingOverlays

Related

google map api markers with realtime data

I currently have realtime analytics php api. It has this entity named $resulting. If I do print_r($resulting); it returns for example (if only 1 user is online):
Array ( [0] => Array ( [0] => Arnhem [1] => 5.898730 [2] => 51.985104 [3] => Chrome [4] => DESKTOP [5] => / [6] => 1 ) )
Now, later on in the same file, I have the google maps javascript api.
It has markers in the form of:
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
As placeholder for now.
What I want to do, is have in the coords: section have the lat: and lng: be the appropriate values from $resulting.
Also, I want to have as many markers as there are users online.
Now, I have tried everything I can think of, but I can't get it to work.
I have tried for example:
const results = <? php echo json_encode($resulting); ?>;
let markers = [];
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
}
};
}
but then the maps won't load anymore.
I have tried looping, foreach, trying to get the lat: and lng: to update with the values returned by $resulting, but whatever I do it simply won't work.
Can anybody help me and get this working?
Thanks.
edit:
adding the index.php file as requested:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php
require_once __DIR__ . '/../google/vendor/autoload.php';
$analytics = initializeAnalytics();
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . 'MY KEY FILE LOCATION';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
/**
* 1.Create and Execute a Real Time Report
* An application can request real-time data by calling the get method on the Analytics service object.
* The method requires an ids parameter which specifies from which view (profile) to retrieve data.
* For example, the following code requests real-time data for view (profile) ID 56789.
*/
$optParams = array(
'dimensions' => 'rt:city, rt:longitude, rt:latitude, rt:browser, rt:deviceCategory, rt:pagePath');
try {
$resultsrealtime = $analytics->data_realtime->get(
'ga:MY GOOGLE CLIENT ID',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
/**
* 2. Print out the Real-Time Data
* The components of the report can be printed out as follows:
*/
$resulting = $resultsrealtime->getRows();
function test() {
if(count($resulting == false)){
return;
}
else if(count($resulting) > 0){
foreach ($resulting as $resultingTwo => $resultingThree) {
foreach ($resultingThree as $resultingFour){
echo $resultingFour.'<br />';
}
}
} else {
echo 'No visitors';
}
}
?>
<script>
// Map options
function initMap(){
var options = {
zoom:7,
center:{lat:52.0907, lng:5.1214}
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
// Loop through markers
for(var i = 0; i < markers.length; i++){
// add Marker
addMarker(markers[i]);
}
// Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
//icon:props.iconImage
});
// Check for custom icon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check for content
if(props.content){
// Set content
// Info Window
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('mouseover', function(){
infoWindow.open(map, marker);
// Reset Info Window
setTimeout(function(){
infoWindow.open()
}, 500);
}, false);
}
}
}
</script>
<div id="data"><p><?php $test = json_encode($resulting); print_r($test);?></p></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Also, what the json_encode returns with 2 users online:
[["Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"],["Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1"]]
You should also assign the map object to the marker (assuming your map object is named map )
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
},
map: map
};
}
To help you identify the issue, it would be useful to see the rest of your javascript code for the map api, as well as the array when there's more than one user after running it though json_encode(). That said, try the following:
const results = <? php echo json_encode($resulting); ?>;
for(let i = 0; i < results.length; i++) {
let marker = new google.maps.Marker({
position: {lat: results[1], lng: results[2]},
content: '<h1>' + results[0] + </h1>,
map: map
});
}
Edit:
I don't have Composer installed in the directory I tested your code in, and I haven't worked much with the Google realtime API, but the following javascript will work given the output you listed for $resulting. You'll have to tweak things depending on where your custom icons are coming from, but that should be pretty straightforward.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php $resulting = array(array("Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"), array("Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1")); ?>
<script>
const resultingArr = <?php echo json_encode($resulting); ?>;
function initMap() {
var options = {
zoom: 7,
center: {
lat: 52.0907,
lng: 5.1214
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
function mapMarkers(props) {
const marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
const infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener('mouseover', function() {
infoWindow.open(map, marker);
});
marker.addListener('mouseout', function() {
infoWindow.close();
});
}
for (let i = 0; i < resultingArr.length; i++) {
mapMarkers({
coords: {
lat: parseFloat(resultingArr[i][2]),
lng: parseFloat(resultingArr[i][1])
},
content: '<h3>' + resultingArr[i][0] + '</h3>'
})
}
};
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Hope this helps!

Can't change the icon of a Google Maps marker from a PHP file

I'm using google maps API to make a map that retrieves data from the database and shows the corresponding markers on the map. I did this by following these instructions: https://developers.google.com/maps/articles/phpsqlajax_v3
What I'm now trying to do is create a page (called add_marker.php) that has a draggable marker so that the user can then add the new marker to the database based on the coordinates. I want to be able to see the other markers when I'm on this page. I also include the map code in all the pages so I don't want it to change drastically just for this page, so my approach is the following: Make the draggable marker invisible in all the pages except for the add_marker page by setting the icon setting to an empty string " ". Now the problem is, I can't change the icon's image so I can see it in the particular page I want it visible. I've searched quite a bit here in stackoverflow and found some solution, but none of these worked.
The error that I get is: add_marker.php:9 Uncaught Reference Error: drag_marker is not defined
(Even though I've made the marker variable global)
The code is the following:
map_code.php (This is the page that I made with the help of the link and is almost identical to that code except for some variable names. It's included in the files that use the map)
Any help would be greatly appreciated
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY"
type="text/javascript"></script>
<script type="text/javascript">
var drag_marker;
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.511769, 22.371699),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("phpsqlajax_genxml.php", 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("name");
var content = markers[i].getAttribute("content");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var content = markers[i].getAttribute("content");
var icon = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
});
bindInfoWindow(marker, map, infoWindow, content, name);
}
});
*var uluru = {lat: 37.52, lng: 22.37};
drag_marker = new google.maps.Marker({
icon: " ",
draggable: true,
position: uluru,
map: map
});*
}
function SelectElement(valueToSelect)
{
var element = document.getElementById("markerList");
element.value = valueToSelect;
}
function bindInfoWindow(marker, map, infoWindow, html, name) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
infoWindow.setContent("<p>" + name + "<br />" +
html + "<br />");
SelectElement(name);
});
}
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: 99.5%; height: 40%"></div>
</body>
</html>
add_marker.php:
<html>
<head>
<title>My website</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
</script>';
</head>
<body>
<div id="container">
<div id="header">
<h1><img src="logo.png" align="center" alt="logo" style="width:300px;height:60px;"><img src="gavlab.png" align="right" alt="logo" style="width:200px;height:55px;"></h1>
</div>
<div id="content">
<div id="nav">
<h3>Πλοήγηση</h3>
<ul id="menu">
<li>Homepage</li>
<li align="left">Map</li>
<li>Admin log-in</li>
<li>info</li>
<li>Contact</li>
</ul>
</div>
<div id="main">
<h6 align="center">Map</h6>
<?php include("map_code.php"); ?>
<div align="center" id="admin_menu">
<?php
error_reporting(E_ALL & ~E_NOTICE ^ E_DEPRECATED ^ E_WARNING );
//http://www.clker.com/cliparts/e/3/F/I/0/A/google-maps-marker-for-residencelamontagne-hi.png
// icon:"http://maps.google.com/mapfiles/ms/icons/red-dot.png",
SESSION_START();
if($_SESSION['username'] == "admin"||$_SESSION['username'] == "username"){
echo '<p align="center" style="color:#8A2908"> Welcome εδώ.</p>';
$con= mysql_connect('localhost','root','');
mysql_set_charset('utf8');
mysql_select_db('qr code');
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con);
$sql="SELECT * FROM array1";
$records=mysql_query($sql);
echo '<form id="main_form" name = "add_new_marker" action="marker_info.php" method="post">';
'</form>';
}
else echo '<p align="center" style="color:#8A2908">Please log in εδώ.</p>';
?>
</div>
</div>
</div>
<div id="footer">
Copyright © 2016 Name Here
</div>
</div>
</body>
</html>
You are attempting to use the drag_marker variable before it is defined (and probably also before it is initialized, look at the HTML/JavaScript rendered in the browser).
To deal with the timing issue, try:
google.maps.event.addDomListener(window, 'load', function() {
drag_marker.setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
}):

How to have my bing maps accept real time lat and long coordinates and track my athlete live along the map

I have just added bing maps and API to my in development site however I am needing some help understanding how to have my code accept live updating lat and long coordinates and have my map update the marker in regards to these values.
Currently this is what I have but part of the code was designed for google maps which I replaced the words google with Microsoft hoping for the best.
Please be gentle I am new to coding
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 400px; height: 400px;'></div>
<script type='text/javascript'>
// Setting boundary and loading map
function loadMapScenario() {
var bounds = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(29.332823, -81.492279), new Microsoft.Maps.Location(28.435825, -81.622231));
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Bing Maps Key',
maxBounds: bounds
});
// Highlighting the border of bounds on the map
var boundsBorder = new Microsoft.Maps.Polyline([bounds.getNorthwest(),
new Microsoft.Maps.Location(bounds.getNorthwest().latitude, bounds.getSoutheast().longitude),
bounds.getSoutheast(),
new Microsoft.Maps.Location(bounds.getSoutheast().latitude, bounds.getNorthwest().longitude),
bounds.getNorthwest()], { strokeColor: 'red', strokeThickness: 2 });
map.entities.push(boundsBorder);
}
</script>
<script>
function getReverseGeocodingData(lat, lng) {
var latlng = new Microsoft.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new Microsoft.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== Microsoft.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == Microsoft.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
</script>
The Bing Maps V8 team actually has a documented code sample on how to do exactly this here: https://msdn.microsoft.com/en-us/library/mt712803.aspx

How can I read the json data from json file in google map api

I am trying to make a google map api with markers, which will show the latitude and longitude of some places.I am trying to do this with json file but it is not working..
here is my code ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cluster Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var markers = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var center = new google.maps.LatLng(43.474144,-112.03866);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
markMultiple();
}
function markMap(latLng, content){
var marker = new google.maps.Marker({
position: latLng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
markers.push(marker);
}
function markMultiple(){
$.parseJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-container">
<div id="map"></div>
</div>
</body>
please help me..
Engineer was right, you need to use $.getJSON method, $.parseJSON takes a JSON string, it doesn't load an external file.
getJSON: http://api.jquery.com/jQuery.getJSON/
parseJSON: http://api.jquery.com/jQuery.parseJSON/
I put your code in a jsFiddle and it is working with getJSON and an alternative test JSON file (you didn't provide the original test.json you're using).
$.getJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
http://jsfiddle.net/WYfjv/
If your code is not working maybe your JSON is not well formatted (try JSONLINT to test it). Also, if you are already improving, I would advise to use a normal for loop rather than $.each :)

Google Maps how to get to show only one marker?

i've been dealing with this couple of hours and i still cant figure how to do it.
my objective is to display only one marker when searching addresses close to each other.
below you have the code i use in my html in order to search for addresses, note - i'm developing a windows application that does such, in which case you might find some missing stuff to do actions by clicking buttons since this is done via .NET windows application
html code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
var marker;
var markersArray = [1];
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
reading previous posts i know that if/else statement has to be used but cant get it right.
your help is very appreciated.
Leo P.
You can add a small bit of code to the beginning of your Geocode function that will remove the previous marker before setting a new one. Try this:
function geocode(address){
if (marker) {
marker.setMap(null);
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
Create only one marker as a global variable and change its position as needed. Like that you also save memory because you're not creating a new marker object on each request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
html, body {width:100%; height:100%}
</style>
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var marker;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
// Create a single marker, (global variable), and don't give it a position just yet.
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
});
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Position the marker
marker.setPosition(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Categories

Resources