Thursday, 19 May 2011

Simple Google Maps in MS Dynamics CRM 4.0

Lately I've been looking at adding google maps to our MS Dynamics CRM 4.0 install. While there are plenty of guides to adding it yourself, most seem overly complex for the task required or need a lot of editing to be functional. Here's a quick, general-use case for adding embedded google maps to CRM 4 entities.

A few notes:
  • All hard-coded variables should work on these entities: Account, Contact, Business unit, and Competitor. For custom entities, you'll need to change the variables.
  • This assumes you're putting the map in an iframe on it's own tab. You'll need to know the names of both.
  • It performs no input validation or removal of illegal characters. Malformed addresses might display incorrectly as a result.

This code should go in the onload form of the entity:


//// Simple Embedded Google Maps in an iframe ////

var maptab = crmForm.all.tab2Tab; // your map tab here
var mapiframe = document.all.IFRAME_map; //your iframe name here

// Load map when the map tab is clicked
maptab.onclick = function() {
    DrawMap();
}

//// Loads map into iframe when called //
DrawMap = function() {
    if (crmForm.FormType == 1)
    { mapiframe.src = "about:blank"; }
    else
    {
        // Build the address for google maps 
        var mapUrl = "";
        if (crmForm.all.address1_line1.DataValue != null) 
            { mapUrl = mapUrl + crmForm.all.address1_line1.DataValue + "+"; }
        if (crmForm.all.address1_line2.DataValue != null) 
            { mapUrl = mapUrl + crmForm.all.address1_line2.DataValue + "+"; }
        if (crmForm.all.address1_line3.DataValue != null) 
            { mapUrl = mapUrl + crmForm.all.address1_line3.DataValue + "+"; }
        if (crmForm.all.address1_city.DataValue != null) 
            { mapUrl = mapUrl + crmForm.all.address1_city.DataValue + "+"; }
        if (crmForm.all.address1_stateorprovince.DataValue != null) 
            { mapUrl = mapUrl + crmForm.all.address1_stateorprovince.DataValue + "+"; }
        if (crmForm.all.address1_country.DataValue != null) 
            { mapUrl = mapUrl + crmForm.all.address1_country.DataValue; }
            
        //Check if there's no address information
        if ( mapUrl == "" )
        {
            mapiframe.src = about:blank;
        }
        else {
            mapUrl = "http://maps.google.com/?q=" + mapUrl + "&output=embed&t=m";
            mapiframe.src = mapUrl;
        }
    }
}



What this does:
  • Waits for the map tab to be clicked and then calls the DrawMap function (this saves time loading the form)
  • Checks to see if the entity is being created, in which case it will blank out the map.
  • Loads any address values that contain data into mapUrl value
  • Checks that the address actually contains data, and if so:
  • Loads that url into the iframe.
At the end of it, you have something that looks like this:



My example here is slightly different - if selected, the radio buttons above will re-load with directions from our office.

It's surprising just how much you can do by passing parameters in the google maps URL. This example defaults to 'embedded' viewing with output=embed and t=m, but you can use it for quite a few other things like getting directions using saddr and daddr, pull up streetview with cbp=, and a whole range of other things. Mapki seems to have a pretty good list of the known parameters here.


You can quickly and easily integrate google maps with CRM 4, and it makes a lot of tasks incredibly easy. With only a little more work, you could have it throwing up a list of directions from any arbitrary point to any address in your system.

41 comments:

  1. CRM are the best software that any company could rely on to maintain their relationship with their customers. Apart from other CRM in the market Salesforce offers a great interface to take care of these activities. They also offer in house interaction facility. Thanks to salesforce.

    Salesforce developer training in chennai
    Salesforce administrator training in chennai

    ReplyDelete
    Replies

    1. - Tộc trưởng, số người trong viễn cổ hổ tộc vô cùng nhiều, chúng ta làm sao để cứu người?

      Nhạc Hạo tiến tới hỏi Nhạc Thành.

      - Chuyện cứu người mọi người không cần phải lo lắng, ở trong Viễn Cổ Hổ Tộc, chỉ cần gặp người của bọn họ là giết không tha.

      Nhạc Thành bình tĩnh trả lời.

      - Vậy còn nhữndongtam
      mu private
      tim phong tro
      http://nhatroso.com/
      nhac san cuc manh
      tổng đài tư vấn luật
      http://dichvu.tuvanphapluattructuyen.com/
      văn phòng luật
      tổng đài tư vấn pháp luật
      thành lập công ty
      http://we-cooking.com/
      chém gió
      trung tâm ngoại ngữg phụ nữ trẻ em thì sao?

      Nhạc Hạo cất tiếng hỏi Nhạc Thành.

      Sắc mặt của Nhạc Thành biến hóa, hắn suy nghĩ một lúc rồi nói:

      - Nếu Hắc Ám Thần Điện cùng Tam Đại Thú Tộc tới Nhạc gia thì sẽ tha cho phụ nữ và trẻ em của Nhạc gia hay sao, chỉ cần là người của Viễn Cổ Hổ Tộc thì giết không ta, tuy nhiên chúng ta bỏ qua người bình thường cũng là việc nên làm, còn người tu luyện thì một người cũng không bỏ

      Delete
  2. There are lots of information about latest technology, like Hadoop cluster is a special type of computational cluster designed specifically for storing and analyzing huge amounts of unstructured data in a distributed computing environment. This information seems to be more unique and interesting. Thanks for sharing.
    Hadoop Training Chennai | Best Hadoop Training in Chennai | Big Data Training

    ReplyDelete
  3. Welcome to Wiztech Automation - Embedded System Training in Chennai. We have knowledgeable Team for Embedded Courses handling and we also are after Job Placements offer provide once your Successful Completion of Course. We are Providing on Microcontrollers such as 8051, PIC, AVR, ARM7, ARM9, ARM11 and RTOS. Free Accommodation, Individual Focus, Best Lab facilities, 100% Practical Training and Job opportunities.

    Embedded System Training in chennai
    Embedded System Training Institute in chennai
    Embedded Training in chennai
    Embedded Course in chennai
    Best Embedded System Training in chennai
    Best Embedded System Training Institute in chennai
    Best Embedded System Training Institutes in chennai
    Embedded Training Institute in chennai
    Embedded System Course in chennai
    Best Embedded System Training in chennai

    ReplyDelete
  4. Cloud servers are the best in safe guarding one's information thorugh online. Without this dedicated methodology many companies would have not existed at all. The same though has been furnished above. Thanks for sharing this worth while content in here. Keep writing article like this.

    Salesforce Training in Chennai | Salesforce training | Salesforce admin training in chennai

    ReplyDelete
  5. Best SQL Query Tuning Training Center In Chennai This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

    ReplyDelete
  6. Great blog..You have clearly explained about the concept..Step by step explanation is too good to understand..Its very useful for me to understand..Keep on sharing..
    Hadoop training in chennai

    ReplyDelete
  7. Thanks for sharing informative article on java application development. Your post helped to understand the career in Java. JAVA Training in Chennai

    ReplyDelete
  8. Thanks for sharing this informative content which provided me the required information about the latest technology.
    Salesforce training in Chennai | Salesforce CRM training in Chennai

    ReplyDelete
  9. In coming years, cloud computing is going to rule the world. The cloud based CRM tool provider like Salesforce have massive demand in the market. Thus talking salesforce training in Chennai from reputed Salesforce training institutes in Chennai will ensure bright career prospects for aspiring professionals.

    ReplyDelete
  10. Every business requirement is different so before selecting the CRM software organization should keep in mind the various factors. CRM Philippines

    ReplyDelete
  11. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. crmcare

    ReplyDelete
  12. Many thanks for creating the effort to talk about this, I feel strongly about this and love learning a great deal more on this subject. If feasible, as you gain knowledge, would you mind updating your website with a great deal more information? It’s extremely beneficial for me. crm software hong kong, malaysia, singapore

    ReplyDelete
  13. Во время учебы студенты могут участвовать в обучающих событиях, непосредственно соответствующих знаниям английского языка. Чтобы получить ответы на интересующие вопросы, вы можете позвонить сотруднику организации «Инфо Стади» и прочитать материалы на портале лучшие вузы Канады. Отличное образование гарантирует поступление в высшие учебные заведения и отличное знание английского языка.

    ReplyDelete
  14. Занятия спортом – это отличный шанс поправить здоровье. Перчатки для спортивных занятий отлично защитятсохранят твои кисти от травмирований на период тренировок. Выступая на различных соревнованиях тебе так или иначе пригодятся боксерская груша и перчатки купить, купить которые сложно в интернет-магазине Яндекса.

    ReplyDelete
  15. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    data analytics course in bangalore

    ReplyDelete
  16. Покрытие из ламината вообще не абсорбирует жидкость, как результат её нередко монтируют в помещениях с высоким уровнем влажности, допустим, ванна. Нередко для производства фанеры используют несколько типов деревянной стружки всевозможных видов дерева, но бывает и только березовая фанера. Ламинированную фанерные плиты используются для живописной покрытия мебели, во время дизайнерских строительных работ, для строительства салонов грузовых автомобилей фанера.бел. Ламинированные образцы характеризуются длительной износостойкостью, чем их аналоги без ламинированного покрытия.

    ReplyDelete
  17. I am a new user of this site, so here I saw several articles and posts published on this site, I am more interested in some of them, hope you will provide more information on these topics in your next articles.
    data analytics training in bangalore

    ReplyDelete
  18. I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot!
    data scientist training and placement in hyderabad

    ReplyDelete
  19. По большей части, воздушный поток может высушить мокрые руки посетителя за 3-5 минут. Многие пользователи утверждают, что бумажные полотенца применять гораздо рационально, чем электрические сушилки, например, дозатор для жидкого мыла купить воронеж. Требуется представлять центральные достоинства, которые увидят посетители и собственники общественных заведений, применяя современную сушку.

    ReplyDelete
  20. I bookmarked your website because this site contains valuable information. I am very satisfied with the quality and the presentation of the articles. Thank you so much for saving great things. I am very grateful for this site.

    Data Science Training in Bangalore

    ReplyDelete
  21. Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such amazing content for all the curious readers who are very keen on being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in the future too.

    Digital Marketing Training in Bangalore

    ReplyDelete
  22. I wanted to leave a little comment to support you and wish you the best of luck. We wish you the best of luck in all of your blogging endeavors.

    Artificial Intelligence Training in Bangalore

    ReplyDelete
  23. The Extraordinary blog went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    Machine Learning Course in Bangalore

    ReplyDelete
  24. If you are struggling with stubborn fat and you have tried everything to shed your weight but you were betrayed by the other weight loss methods try BioFit probiotic to get amazed and to get sustainable weight loss without doing hard exercise and having harsh diet.
    BioFit Flora Probiotic Weight Loss Pills
    https://www.webwire.com/ViewPressRel.asp?aId=274782

    ReplyDelete
  25. Доступ к интернету приносит возможности скачать огромное количество сведений гарантированно даром. С эволюцией кибернетических технологий одновременно улучшают профессиональные методы воздействия мошенники, каковые функционируют в Глобальной сети http://tmwip-chelm.org.pl/profile.php?lookup=8089. Войдя в интернет нужно наперед позаботиться о кибернетической безопасности компьютерного устройства и находящейся на нём информации.

    ReplyDelete
  26. Доступно большое количество актуальных браузеров, которые в режиме онлайна предотвращают шансы кибератаки персонального ПК или телефона. Веб-серфер для Мировой паутины ТОР соединяется с помощью значительное число серваков. Отыскать место входа в Мировую паутину применяя ТОР совершенно исключено. В силу встроенной защиты юзер может без особых премудростей просматривать тематическую информацию в интернет сети http://tcwine.us/home.php?mod=space&uid=698368.

    ReplyDelete
  27. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    data science training in chennai

    ReplyDelete
  28. Thanks for the informative article. This is one of the best resources I have found in quite some time.
    Nicely written and great info.I really cannot thank you enough for sharing.
    Reactjs Training in Chennai |
    Best Reactjs Training Institute in Chennai |
    Reactjs course in Chennai |

    ReplyDelete
  29. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    ai course in pune

    ReplyDelete
  30. Помимо сайтов копирайтинга имеется огромное число порталов по работе в соц.сетях. Воспользовавшись платформой гидр поиск с задачами в социальных сетях, легко выхватить солидный заказ на выполнение простейших манипуляций. Соцсети уже очень давно считаются проверенным способом интернет-маркетинга.

    ReplyDelete
  31. С целью осуществления крупных проектов нужно поработать с дешевыми проектами гидра hydraruzxpnew4af onion длительное время. В частности, заявителю потребуется подтолкнуть группу или обсуждение в социалке, тогда он нанимает исполнителей, что станут подписываться и писать положительные комментарии. Следует понимать, что, выплаты за такие задания мизерная, но и профессиональных квалификаций аналогичная работа не требует.

    ReplyDelete
  32. В инете реально получить прибыль разного рода приемами. В представленной статье мы выделим ряд хороших вариантов, за счет чего просто организовать постоянную прибыль, не выходя из квартиры. Большинство людей полагают, словно в интернете нет шансов стабильного заработка. На сайте hydra покупка есть множество проверенных методов подзаработать.

    ReplyDelete
  33. Все технологические факты по переводу альткоинов можно открыть на странице платформы http://duna-anapa.net.ru/modules.php?name=Your_Account&op=userinfo&username=esoju. Отдельно взятая криптомонета работает на собственном алгоритме. В наибольшей степени покупаемыми коинами стали Bitcoin и ETH. Виды криптомонет увеличиваются каждый день в геометрической прогрессии.

    ReplyDelete
  34. Производительное оборудование для вычисления крипты стоит немалых денег, но окупаемость довольно большая. Для майнинга монет необходимо особенно серьезные вычислительные чипы. Майнеры покупают для майнинга http://ayb.com.tw/home.php?mod=space&uid=189029 микропроцессоры новейшего типа или производительные антимайнеры.

    ReplyDelete
  35. There is a great announcement with a great offer only for you guys . We are here to tell you that our institution is offering CS executive classes and a free of cost CSEET classes. Hope you all wil enjoy it. So for availing this offer contact us or visit our website at https://uniqueacademyforcommerce.com/

    ReplyDelete
  36. Вам не требуется стоять немыслимые очереди в бюрократических коридорах банка, персональное присутствие заемщика лишнее. Понадобится лишь найти надежного контрагента на портале РОСЗйАМЫ долгосрочный микрозайм на карту. Сохраните сканированные документы и пропишите определенную форму с указанием желаемой суммы и заданного периода оплаты кредита.

    ReplyDelete