Google Maps how to get to show only one marker? - javascript

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>

Related

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

Google Maps API V3 : How to get multiple path distances using direction from a point A to point B

I can get only one driving distance from point A to point B using google map api v3.
Code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 13px; color: red;">
<div id="map" style="width: 400px; height: 300px;"></div>
<div id="duration">Duration: </div>
<div id="distance">Distance: </div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);
var st=new google.maps.LatLng(51.7519, -1.2578);
var en=new google.maps.LatLng(50.8429, -0.1313);
var request = {
origin: st,
destination:en,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the distance:
document.getElementById('distance').innerHTML +=
(response.routes[0].legs[0].distance.value)/1000 + "killo meters";
alert((response.routes[0].legs[0].distance.value)/1000 + "killo meters");
// Display the duration:
document.getElementById('duration').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
alert( response.routes[0].legs[0].duration.value + " seconds");
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
But I want to get multiple or all possible driving distances using google map api v3. I want to get multiple distances like given below.
There is a provideRouteAlternatives options that can be specified with the directions request parameters to tell the DirectionsService to return multiple results. You can amend your request parameters as follows:
var request = {
origin: st,
destination: en,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
// Returns multiple routes
provideRouteAlternatives: true
};
Your event handler for obtaining the directions can be modified to create a new DirectionsRenderer for each route as follows (ensure you set the correct route index each time, otherwise the DirectionsRenderer will render the first route in the response):
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Create a new DirectionsRenderer for each route
for (var i = 0; i < response.routes.length; i++) {
var dr = new google.maps.DirectionsRenderer();
dr.setDirections(response);
// Tell the DirectionsRenderer which route to display
dr.setRouteIndex(i);
dr.setMap(map);
// Code ommited to display distance and duration
}
}
}
The code where you append the distance and duration will need to be brought into this for loop so it appends the distance and duration for each route. I've ommited this in the code snippet above but it is in the demo Fiddle below.
I've created a Fiddle to demonstrate this.

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 :)

add script to asp.net content page

I have a google map script that works, but I can't figure out how to add it to my asp.net content page. What is the proper way to add the script to the page?
see code:
<%# Page Title="Our Location" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="Location.aspx.vb" Inherits="About_Location" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
##map{ height: 100% }
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server" OnLoad="codeAddress()">
<script type= "text/javascript">
var geocoder;
var map;
var marker;
function codeAddress() {
alert("hello")
//initializes the map
//create geocoder
geocoder = new google.maps.Geocoder();
//set options for the map being created
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create map instance and pass it the myOptions object literal
map = new google.maps.Map(document.getElementById("map"), myOptions);
//geocode to get the lat and lng points of the given address
geocoder.geocode({ 'address': 'New York, New York'}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//if geocoder finds location
//center the map on the latlng points of the given address
map.setCenter(results[0].geometry.location);
map.setOptions({ zoom: 18 });
//create marker and place it on the address
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'New York, New York'
});
}
else {
//if geocoder cannot find location, alert user
alert("Could not find location");
}
});
}
</script>
<div id="map" style="width:700px; height:400px;"></div>
</asp:Content>
Put your script in separate js file, declare it like you did with Google maps script. Then you have to call it, maybe send this "#map" div id as parameter to that script, and not hard code it in javascript.
in this case you want to do that on page load with script manager :
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowGoogleMap", "codeAddress('map');", true);
btw. for google maps you can use Google Maps server control, it's much easier to use managing maps from server side:
http://googlemap.codeplex.com/

Loading city/state from SQL Server to Google Maps?

I'm trying to make a small application that takes a city & state and geocodes that address to a lat/long location. Right now I am utilizing Google Map's API, ColdFusion, and SQL Server. Basically the city and state fields are in a database table and I want to take those locations and get marker put on a Google Map showing where they are.
This is my code to do the geocoding, and viewing the source of the page shows that it is correctly looping through my query and placing a location ("Omaha, NE") in the address field, but no marker, or map for that matter, is showing up on the page:
function codeAddress() {
<cfloop query="GetLocations">
var address = document.getElementById(<cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>).value;
if (geocoder) {
geocoder.geocode( {<cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: <cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</cfloop> }
And here is the code to initialize the map:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(42.4167,-90.4290);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Test"
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
I do have a map working that uses lat/long that was hard coded into the database table, but I want to be able to just use the city/state and convert that to a lat/long. Any suggestions or direction? Storing the lat/long in the database is also possible, but I don't know how to do that within SQL.
You may want to consider the following example:
Using the V2 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
// Prepare this list from ColdFusion
var locations = [
'New York, NY',
'Los Angeles, CA',
'Chicago, IL',
'Houston, TX',
'Phoenix, AZ'
];
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.getLatLng(locations[index], function (point) {
if (point) {
map.addOverlay(new GMarker(point));
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
map.setCenter(new GLatLng(38.00, -100.00), 3);
// Launch the geocoding process
geocoderFunction();
}
</script>
</body>
</html>
Using the V3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
// Prepare this list from ColdFusion
var locations = [
'New York, NY',
'Los Angeles, CA',
'Chicago, IL',
'Houston, TX',
'Phoenix, AZ'
];
var mapOpt = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(38.00, -100.00),
zoom: 3
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOpt);
var geocoder = new google.maps.Geocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.geocode({ 'address': locations[index] }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
// Launch the geocoding process
geocoderFunction();
</script>
</body>
</html>
All you need to do is to render the JavaScript array locations from ColdFusion, instead of using the hardcoded one in the example.
Screenshot from the above example:
You need to actually add the marker to the map using the addOverlay method:
var point = new GLatLng(...);
map.addOverlay(new GMarker(point));
You can also add instances of the Marker class to your map:
map.addOverlay(marker);
See the Map Overlays docs:
http://code.google.com/apis/maps/documentation/javascript/v2/overlays.html

Categories

Resources